PowerShell Variables in PowerShell Scope


Example

The default scope for a variable is the enclosing container. If outside a script, or other container then the scope is Global. To specify a scope, it is prefixed to the variable name $scope:varname like so:

$foo = "Global Scope"
function myFunc {
    $foo = "Function (local) scope"
    Write-Host $global:foo
    Write-Host $local:foo
    Write-Host $foo
}
myFunc
Write-Host $local:foo
Write-Host $foo

Output:

    Global Scope
    Function (local) scope
    Function (local) scope
    Global Scope
    Global Scope