Script scope

The Script scope is shared across all children in a script or script module. The Script scope is a useful place to store variables which must be shared without exposing the variable to the Global scope (and therefore to anyone with access to the session).

For example, the following short script stores a version number in a script-level variable. The functions Get-Version and Set-Version both interact with the same variable:

# Script file: example.ps1 
[Version]$Script:Version = "0.1" 
 
function Get-Version { 
    Write-Host "Version: $Version" 
} 
 
function Set-Version { 
    param( 
        [Version]$version 
    ) 
 
    $Script:Version = $version 
} 
 
Set-Version 0.2 
Write-Host (Get-Version) 

The function Set-Version implements a Local variable in the param block with the same name as the Script scope variable. To access the Script scope variable version, the name must be prefixed with the scope.

Scope confusion:
If variables within a named scope are used, I recommend referencing the scope whenever the variable is used to make it clear where the values originate from.
In the preceding example, that means using $Script:Version in the Get-Version command.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.239.182