Partilhar via


Did you know? #2

Did you know that you can make a variable automatically propagate to new scopes by using the AllScope option?

Normally when you enter a new scope variables are not copied from the parent
scope. Instead we do a lookup for the variable when requested. Anytime the
variable is written to it happens in the local scope. This means that it is
possible to hide constant variables in a parent scope which can lead to
programming mistakes.  The AllScope option automatically copies the variable
to any new child scope which prevents you from accidentally hiding your
constant variable.

Example without AllScope:
MSH > function varInScope { new-variable var -value "new value"; $var }
MSH > new-variable var -value "original value" -option Constant
MSH > $var
original value
MSH > varInScope
new value

Example using AllScope:
MSH > function varInScope { new-variable var -value "new value"; $var }
MSH > new-variable var -value "original value" -option "Constant,AllScope"
MSH > $var
original value
MSH > varInScope
new-variable : A variable with name 'var' already exists.
At line:1 char:35
+ function varInScope { new-variable  <<<< var -value "new value"; $var }
original value

-Jeff Jones