Working with Private Variables

by Oct 18, 2010

PowerShell inherits by default variables downstream so subsequent scopes can "see" the parent variables. If you want to turn off variable inheritance altogether, you should use the prefix "private:." This way, variables will only work in the scope in which they are defined, and will neither inherit upstream or downstream:

$private:a = 1
Function test {
"variable a contains $a"
$a = 2
"variable a contains $a"
}
test
variable a contains
variable a contains 2
$a
1

You should note that defining a variable as private will not overwrite an existing variable. So, if you had previously defined a variable "a" without the private: prefix, you would not be able to turn it into a private variable. To make sure, you should either start a new fresh PowerShell environment, or delete the variable before creating your private variable:

Remove-Variable a -ErrorAction SilentlyContinue

Twitter This Tip!
ReTweet this Tip!