PDF Archive

Easily share your PDF documents with your contacts, on the Web and Social Networks.

Share a file Manage my documents Convert Recover PDF Search Help Contact


Preview of PDF document functionsparamadusers.pdf

Page 1 2 34533

Text preview

Lecture 10 – Functions Continued

Page 3 of 33

The script first gets the value of $variable1. Since $variable1 was not defined in the script scope,
PowerShell automatically goes up the scope tree to find the value. It finds the value in the global scope
and displays: “I am a global variable”.
The script, in the script scope, then changes the value of $variable1 to “I am a script variable”. And then
calls the function scope-demo.
The function scope-demo did not find a value for $variable1 in the function scope, so it climbed the
scope tree and found $variable1 in the script scope and displayed: “I am a script variable”. The value of
$variable1 was changed and the new value inside the function is displayed: “I am a function variable”.
When the function ends, however, the value of $variable1 is lost, and the only value PowerShell can find
is in the script scope, so it displays: “I am a script variable” before the script exits. At the command
prompt, however, if you type $variable1, you will notice that the value is “I am a global variable”
because the global variable was not changed. Child scopes can read, and modify values above the
current scope, but can’t change values in children of the current scope.

Figure 3: Output of Scope-Demo.ps1

In writing PowerShell scripts or functions it is a bad practice to declare a variable and not define its value
within the local scope, because PowerShell will climb the scope tree to assign a value for a variable of
the same name. This could be a problem and cause unexpected problems in your script or function.
Best practice is always to declare variables and assign values in the local scope. Notice how the scopes
worked. $Variable1 was changed as we moved through the script because, up until the Function ScopeDemo was completed, we were checking on the variable from within the same scope it was last
changed. After the Function ended, we moved back into the Script scope where $Variable1 was left
untouched by the function. Then, when the script terminated, we came back out into the Global scope
where the global variable $variable1 hadn’t been modified at all.
Reaching Outside the Local Scope
It is generally regarded as bad practice to modify variables outside of the local scope, but it can be done
using a special, and fairly simple, syntax:
© Seneca College, ICT, 2013