PowerShell for Windows Admins

Feb 26 2018   8:10AM GMT

PowerShell Scope

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

PowerShell Scope has an important impact on the way your code runs. When you run a script or a function in PowerShell it runs it in its own scope. This means that all variables, functions, classes, aliases etc are removed from memory at the end of the script.

Here’s an example

create a class

class test {
[int]$P1 = 1
[int]$p2 = 2

}

Now save the code as test.ps1.
Run the code in the console

PS> .\test.ps1
PS> [test]::new()
Unable to find type [test].
At line:1 char:1
+ [test]::new()
+ ~~~~~~
+ CategoryInfo : InvalidOperation: (test:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

The reason you’re not seeing [test] is that a script runs in its own scope and all variables, functions classes etc are removed at the end of the script’s execution.

You need to dot source the script so that the class remains in memory. You do that by putting a . in front of the script name like this

PS> . .\test.ps1
PS> [test]::new()

P1 p2
— —
1 2

Anything defined in the console is visible to scripts you run but not vice versa.

We spent a lot of time discussing Scope in PowerShell in Action – https://www.manning.com/books/windows-powershell-in-action-third-edition

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: