如何防止命令/脚本改变全局环境

发布于 2024-09-03 21:47:11 字数 421 浏览 7 评论 0原文

我需要从当前的顶级 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦幻的心爱 2024-09-10 21:47:11

我不知道还有什么其他选择。正如@Peter 回答的那样,环境变量是按进程保存的。

此外,如果您在其中创建新的目录和文件,那么您就会更改全局环境。所以剧本并不是完全无辜的。

在你的情况下,我会按照你的建议运行新流程。
如果实在太懒,就放到一个脚本中,然后包装到try/finally中:

--- script.ps1
push-location
try {
  mkdir newdir
  cd newdir
  $env:NEW_VAR = 100
  ni -item f 'newfile.txt'
} finally {
  pop-location
  # delete dir/file?
  remove-item env:NEW_VAR
}

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:

--- script.ps1
push-location
try {
  mkdir newdir
  cd newdir
  $env:NEW_VAR = 100
  ni -item f 'newfile.txt'
} finally {
  pop-location
  # delete dir/file?
  remove-item env:NEW_VAR
}
五里雾 2024-09-10 21:47:11

不存在全球环境这样的东西。当生成新进程时,操作系统会为新进程创建环境的副本。

如果您在单独的进程中运行脚本,那么当它离开时,一切都将完好无损。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文