Private variable

Problem

Attain the value of a private variable declared in a child scope from that scope’s own child scope.

Solution

1
2
3
4
5
6
& {
    $Private:var = 7
    & {
        Get-Variable var -Scope 1 -ValueOnly
    }
}

Declare the private variable var in a ScritBlock’s scope (let’s call it “Scope A”). Next, from the scope of an inner ScriptBlock (we’ll call this one “Scope B”), call the Get-Variable Cmdlet with the appropriate arguments to retrieve only the value of the private variable that is visible only in the parent’s scope (Scope “A”).


Winner: Shay Levy

Share on:
comments powered by Disqus