Variable scoping in PowerShell

You can use scope modifiers or the *-Variable cmdlets.

The scope modifiers are:

  • global used to access/modify at the outermost scope (eg. the interactive shell)
  • script used on access/modify at the scope of the running script (.ps1 file). If not running a script then operates as global.

(For the -Scope parameter of the *-Variable cmdlets see the help.)

Eg. in your second example, to directly modify the global $array:

& {
  $global:array +="s"
  Write-Host $array
}

For more details see the help topic about_scopes.


The PowerShell scopes article (about_Scopes) is nice, but too verbose, so this is quotation from my article:

In general, PowerShell scopes are like .NET scopes. They are:

  • Global is public
  • Script is internal
  • Private is private
  • Local is current stack level
  • Numbered scopes are from 0..N where each step is up to stack level (and 0 is Local)

Here is simple example, which describes usage and effects of scopes:

$test = 'Global Scope'
Function Foo {
    $test = 'Function Scope'
    Write-Host $Global:test                                  # Global Scope
    Write-Host $Local:test                                   # Function Scope
    Write-Host $test                                         # Function Scope
    Write-Host (Get-Variable -Name test -ValueOnly -Scope 0) # Function Scope
    Write-Host (Get-Variable -Name test -ValueOnly -Scope 1) # Global Scope
}
Foo

As you can see, you can use $Global:test like syntax only with named scopes, $0:test will be always $null.