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.
In the ISE, this does appear to work if the script is called using the console window.
However, if I actually use the "Run Script" button, or F5, variables within the script will persist after it is completed.
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.