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"    # Accessible 
} 
 
Test-ThisScope 

When scopes are explicitly named as this, the source of a variable value can be reasonably clear. If the scope prefix is removed, PowerShell attempts to resolve the variable by searching the parent scopes, as follows:

Remove-Variable thisValue -ErrorAction SilentlyContinue 
# This is still "local" scope 
$thisValue = "Some value" 
 
function Test-ThisScope { 
    "From Local: $local:thisValue"      # Does not exist 
    "From Global: $global:thisValue"    # Accessible 
    "Without scope: $thisValue"         # Accessible 
} 
 
Test-ThisScope 

The thisValue variable was created in the global scope. As the function does not have a similarly named variable in its local scope, it walks up the scope hierarchy and picks out the variable from the parent scope.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.41.214