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