April 25th, 2006

Did you know? #2

PowerShell Team
PowerShell Team

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

[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.