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 23433

Text preview

Lecture 10 – Functions Continued

Page 2 of 33

from being able to read or modify items they might otherwise have access to.
When you open the PowerShell console and type at the command line, your local scope is the global
scope. The current scope is referred to as zero and its ancestors are referenced by increasing integers.
For example, if you run a script from the command line, then your local scope is the script scope; the
latter would be 0 and the Global scope would be 1. Then if you run a function, the local scope would be
a function scope and the Global scope would be referred to as 2.
Scopes and Commands
As mentioned earlier, commands executed within one scope will not affect things in another scope
unless explicitly told to do so. For example, if $Variable1 exists in the Global scope and a script runs a
command to set $Variable1 to a different value, the Global version of $Variable1 will remain unaltered
while a copy of $Variable1 is placed in the Script scope with the new value. If a $Variable1 doesn’t exist,
a script will create it within the Script scope by default – not in the Global scope. This is important to
remember as you learn about the actual parent/child relationship between scopes.
The parent/child relationship of scopes in PowerShell is one-way. Commands can see into, and
optionally modify, the current scope, its parent, and any scopes above that. However, they cannot see
or modify things in any children of the current scope.
There are plenty of times where you need a script’s or function’s changes to persist beyond its
completion. This is why functions must be dot-sourced. The latter copies any variables, such $Variable
1 to the Global scope, so it would be available to another function running in the same session.
One exception to the above is a Private scope. Objects in a Private scope are only accessible to
commands run in the scope from which
they were created.
Scopes in Action
To see how scopes work, we will write a
short script called scope-demo.ps1.
Before running your script, type the
following at the command line.
$variable1 = “I am a global variable”.
This will make $variable1 a global
variable, since we are creating it at the
console. Note: this script must be run
from the PowerShell console, DO NOT
use the ISE you will not get the correct
Figure 2: Code to Test Scopes

© Seneca College, ICT, 2013

Type the following code into your ISE,
but run the script from the command