Variable scope
Variables may be declared in a number of different scopes. The scopes are:
Local
Global
Private
Script
- A numeric scope relative to the current scope
Note
More about scopes:
The help document, About_Scopes
(Get-Help about_Scopes
), has more examples and detail.
By default, variables are placed in Local
scope. Access to variables is hierarchical: a child (scopes created beneath a parent) can access variables created by the parent (or ancestors).
Local and Global scope
When creating a variable in the console (outside of functions or script blocks), the Local
scope is Global
. The Global
scope can be accessed from inside a function (child) because it is a parent scope:
Remove-Variable thisValue -ErrorAction SilentlyContinue
$Local:thisValue = "Some value"
"From Local: $local:thisValue" # Accessible
"From Global: $global:thisValue" # Accessible
function Test-ThisScope {
"From Local: $local:thisValue" # Does not exist
"From Global: $global:thisValue" #...