Private scope

The Private scope may be accessed using the private prefix, as follows:

$private:thisValue = "Some value" 

Moving a variable into the Private scope will hide the variable from child scopes:

Remove-Variable thisValue -ErrorAction SilentlyContinue 
# This is still "local" scope 
$private:thisValue = "Some value" 
"From global: $global:thisValue"           # Accessible 
 
function Test-ThisScope { 
    "Without scope: $thisValue"            # Not accessible
"From private: $private:thisValue" # Not accessible "From global: $global:thisValue" # Not accessible } Test-ThisScope

If the stack depth is increased, the variable search can be made to skip a private variable within an intermediate function and reference the variable from an ancestor, as shown here:

PS> function bottom {
$thisValue = "Bottom"
Write-Host "Bottom: $thisValue"
middle
}
function middle {
# Hide thisValue from children
$private:thisValue = "Middle" # Middle only
Write-Host "Middle: $thisValue"
top
}
function top {
Write-Host "Top: $thisValue" # Original value
}
bottom

Bottom: Bottom
Middle: Middle
Top: Bottom
..................Content has been hidden....................

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