header image

PowerShell Scope

Posted by: | February 26, 2018 Comments Off on PowerShell Scope |

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

under: PowerShell

Comments are closed.

Categories