Search notes:

PowerShell: scopes

The following PowerShell items exist in a scope:

Scopes have a hierarchy

Scopes can nest, that is: a scope can contain other scopes.
The containing scope is referred to as the parent scope, the contained scope as its child scope.
The root of all scopes is the global scope.
An item in a child scope that has the same name as an item in one of its parent scopes hides that item.

Accesing items in a parent scope

Within a child scope, it's possible to acess items of its parent scope unless the item is explicitly marked as private (with the :private scope modifier).

Modifying items

An item can be modified in the scope in which it was created.
In a child scope, an item can be modified if the scope is explicitly stated.

Creating a new scope

A new scope can be created
When a new scope is created, PowerShell fills it with some items:

Scope modifiers

global:
local:
private:
script:
using: Required, for example, in a script block that is passed to start-job to access the value of a variable that was defined outside the scriptblock. As per an error message, a using variable can be used only with invoke-command, start-job, or InlineScript in the script workflow.
workflow:
Scope modifiers are applicable to
For example, in order to access a global variable, this is possible with
$global:var = 'value'
In addition, the PSDrive provider adds the following variable namespaces:
alias:
env: to access environment variables
function:
variable:

Example

The following example tries to demonstrate the :global and :script modifiers in a function:
$var = 'assigned in script'

function func() {

 #
 #   Function did not not create its own $var yet, so
 #  $var refers to $script:var
 #
   write-host "  in func: var = $var"

   $var        = 'assigned in function'
   $global:var = 'assigned in function with :global'

 #
 #   Now, htat the function has created its own $var,
 #  $var refers to the function's $var, not to $script:var
 #
   write-host "  in func: var = $var"

 #
 #   Use modifiers to explicitely state what variable
 #   is referred to:
 #
   write-host "  in func: script:var = $script:var"
   write-host "  in func: global:var = $global:var"

}

write-host "var = $var"
write-host "calling func"
func
write-host ""
write-host "var = $var"
write-host "script:var = $script:var"
write-host "global:var = $global:var"

#
# script prints:
#
#    var = assigned in script
#    calling func.
#      in func: var = assigned in script
#      in func: var = assigned in function
#      in func: script:var = assigned in script
#      in func: global:var = assigned in function with :global
#
#    var = assigned in script
#    script:var = assigned in script
#    global:var = assigned in function with :global
Github repository about-PowerShell, path: /language/scope/function.ps1

See also

The dot sourcing operator (.) can be used to create items in the current scope.
Create a global variable in a function.

Index