在PowerShell中,作用域应该防止脚本中的对象(变量,别名,函数等)影响全局环境。这似乎在命令行上可以正常工作,但在ISE中却不能。
这是控制台中的演示。我检查$x
是否未在全局范围中定义,显示的内容,ScopeTest.ps1
然后运行它,最后检查是否$x
再次定义。如预期的那样,$x
仅在脚本范围内创建和使用该脚本,并且在脚本终止后不会在全局环境中保留。
在ISE中,如果使用控制台窗口调用脚本,这似乎可以正常工作。
但是,如果我实际使用“运行脚本”按钮或F5,则脚本中的变量在完成后将保留。
如果脚本假定脚本将在干净的环境中启动,则这可能会使脚本编写和故障排除变得有些困难(即:脚本中设置的任何变量都不应该存在。)。为什么ISE会以这种方式运行?
这个问题的答案只是略微涉及到该主题,提到了“点源”,但是我希望在这里得到更详尽的解释。另外,如果存在有关为什么脚本在ISE中与在控制台中以不同方式运行的文档,那么参考也将是不错的选择。
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.
如果您不希望在脚本完成后将变量Remove-Variable
保留在Shell中,则应该使用它们。
例如:
Remove-Variable x
您可以通过单击“文件”->“新Powershell”选项卡将Powershell的“干净”实例添加到ISE。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句