Getting Variable Value in Parent Scope

by May 8, 2014

If you define variables in a function, then these variables live in function scope. To find out what the value of the variable is in the parent scope, use Get-Variable with the parameter -Scope:

$a = 1

function test
    $a = 2
    $parentVariable = Get-Variable -Name a -Scope 1


When the script calls "test", the function defines $a and sets it to 2. In the caller scope, variable $a is 1. By using Get-Variable, the function can find out the variable value in the parent scope.

Twitter This Tip! ReTweet this Tip!