Shell – Why does the PowerShell ISE not isolate script variables to the script scope

powershell

In PowerShell, scoping is supposed to keep objects (variables, aliases, functions, etc) in scripts from affecting the global environment. This appears to work fine at the command line, but not in the ISE.

Here's a demonstration in the console. I check to see that $x is not defined in the global scope, show the contents of ScopeTest.ps1 and then run it, and lastly I check to see if $x is defined again. As expected, $x is only created and used within the scope of the script and does not persist in the global environment after the script has terminated.

enter image description here

In the ISE, this does appear to work if the script is called using the console window.

enter image description here

However, if I actually use the "Run Script" button, or F5, variables within the script will persist after it is completed.

enter image description here

This can make writing and troubleshooting scripts a bit difficult, if the script assumes that it will be starting from a clean environment (i.e.: Any variables set within the script should not already exist.). Why does the ISE behave in this way?

An answer to this question touches on the topic just slightly, mentioning "dot-sourcing", but I'm hoping to get a more thorough explanation here. Also, if documentation exists as to why the script is run differently in the ISE than from the console, a reference would be nice too.

Best Answer

In your script examples you created variables and you didn't destroy them at the end of your script. The ISE creates a live instance of powershell which loads and runs the script when you click run. The difference is that the integrated shell can continue the script. This is ideal for debugging the environment and for creating scripts as you go. This way you don't have to keep running your script over and over (there are situations where this wouldn't be ideal) to make sure the next line of code worked. You type it in the shell, and if it works, you add it to the script section.

This behavior is perhaps best described here: http://technet.microsoft.com/en-us/library/dd819480.aspx

Relevant Excerpt:

All panes in ISE are always in the same scope.

If you don't want your variables to live in the shell after your script has completed then you should Remove-Variable them.

For example:

Remove-Variable x

You can add a "clean" instance of powershell to the ISE by clicking File->New Powershell Tab

Related Question