如何防止命令/脚本改变全局环境
我需要从当前的顶级 shell 运行脚本块/脚本,并且希望它们保持全局范围不变。
到目前为止,我只能想到以下可能性:
powershell -file <script>
powershell -noprofile -command <scriptblock>
问题是,它们非常慢。
例如,我希望能够执行以下操作:
mkdir newdir
cd newdir
$env:NEW_VAR = 100
ni -item f 'newfile.txt'
...这样我的 shell 的工作目录就不会更改,并且 $env:NEW_VAR
不会在全局范围内设置。
还有其他替代方案可以实现此目的吗?
I need to run scriptblocks/scripts from the current top-level shell and I want them to leave the global scope unmodified.
So far, I've only been able to think of the following possibilities:
powershell -file <script>
powershell -noprofile -command <scriptblock>
The problem is, that they are very slow.
For instance, I would like to be able to do:
mkdir newdir
cd newdir
$env:NEW_VAR = 100
ni -item f 'newfile.txt'
...so that my shell's working dir wouldn't change and $env:NEW_VAR
wouldn't be set in the global scope.
Are there any more alternatives to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道还有什么其他选择。正如@Peter 回答的那样,环境变量是按进程保存的。
此外,如果您在其中创建新的目录和文件,那么您就会更改全局环境。所以剧本并不是完全无辜的。
在你的情况下,我会按照你的建议运行新流程。
如果实在太懒,就放到一个脚本中,然后包装到try/finally中:
I don't know about any other alternative. Environment variables are kept per process as @Peter answered.
Futhermore if you create new dir and a file in there, then you alter the global environment. So the script is not completely innocent.
In your case I would run new proccess as you suggested.
If it is too lazy, place it into a script and wrap it into try/finally:
不存在全球环境这样的东西。当生成新进程时,操作系统会为新进程创建环境的副本。
如果您在单独的进程中运行脚本,那么当它离开时,一切都将完好无损。
There is no such thing as a global environment. When spawning a new process, the OS creates a copy of the environment for the new process.
if you run the scripts in a separate process, when it leaves everything will be intact.