Scope

Variables defined outside a block are usable inside a block. Variables defined inside a block are deleted when the block goes out of scope:

Clear-Host
$var = 42
&{
    Write-Host "Inside block: $var"    # 42
    $localvar = 33
}
Write-Host "Outside block: $var"       # 42
Write-Host "Local var: $localvar"      # null

If an outside variable is changed inside a block, the original is unmodified:

Clear-Host
$var = 42
&{ $var = 33; Write-Host "Inside block: $var" }    # 33
Write-Host "Outside block: $var"                   # 42

The Get-Variable cmdlet lets you access variables outside the current scope. Scope 0 is the current scope, 1 is its parent, 2 grandparent, etc:

Clear-Host
$var = 42
&{
    $var = 33;
    Write-Host "Inside block: $var"                                 # 33
    Write-Host "Parent: " (Get-Variable var -valueOnly -scope 1)    # 42
 }
Write-Host "Outside block: $var"                                    # 42

Can also set the value of a variable outside the current scope using Set-Variable (bad practice, can have unintended side effects. Instead return the value so the user can do what they want with it):

Clear-Host
$var = 42
&{
    Set-Variable var 33 -scope 1
    Write-Host "Inside block: $var"    # 33
}
Write-Host "Outside block: $var"       # 33

Can make a variable global, making it accessible/modifiable from any scope:

Clear-Host
$global:var = 42
&{ $global:var = 33 }
Write-Host "Outside block: $var"    # 33

Can also make a variable private, making it inaccessible outside the current scope:

Clear-Host
$private:hidden = 42
&{ Write-Host "Inside block: $hidden" }    # null
Write-Host "Outside block: $hidden"        # 42

results matching ""

    No results matching ""