如果不存在,如何在PowerShell中设置env变量? [英] How do I set an env variable in PowerShell if it doesn't exist?

查看:514
本文介绍了如果不存在,如何在PowerShell中设置env变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我惊讶的是,在谷歌搜索了一段时间之后,没有得到这种常见情况的答案...

I'm surprised that I didn't get the answer for this common scenario after Googling for while...

如果环境变量不存在,如何在PowerShell中设置?

How can an environment variable in be set in PowerShell if it does not exist?

推荐答案

以下代码定义环境变量FOO(如果尚不存在).

The following code defines environment variable FOO, if it doesn't exist yet.

if (-not (Test-Path env:FOO)) { $env:FOO = 'bar' }

注意:此新定义的环境变量仅在当前进程及其创建的任何子进程中存在(例如,当您从ISE启动新的PowerShell会话时). 谢谢, PetSerAl .

Note: This newly defined environment variable will only exist for the current process and any child processes it creates (e.g., when you start a new PowerShell session from the ISE). Thanks, PetSerAl.

以下内容主要由 Ansgar Wiechers 贡献,并由Mathias R. Jessen :

The following was mostly contributed by Ansgar Wiechers, with a supplement by Mathias R. Jessen:

在Windows [*] 上,如果要持久地定义环境变量 ,则需要使用静态的SetEnvironmentVariable() 方法的"https://docs.microsoft.com/zh-cn/dotnet/api/System.Environment.SetEnvironmentVariable" rel ="noreferrer"> SetEnvironmentVariable() 方法docs.microsoft.com/zh-CN/dotnet/api/System.Environment"rel =" noreferrer> [System.Environment] 类:

On Windows[*], if you want to define an environment variable persistently, you need to use the static SetEnvironmentVariable() method of the [System.Environment] class:

# user environment
[Environment]::SetEnvironmentVariable('FOO', 'bar', 'User')

# system environment (requires admin privileges)
[Environment]::SetEnvironmentVariable('FOO', 'bar', 'Machine')

请注意,这些定义在将来会话(进程)中生效,因此为了定义 current 进程的变量, ,另外运行$env:FOO = 'bar' ,该功能实际上与[Environment]::SetEnvironmentVariable('FOO', 'bar', 'Process')相同.

Note that these definitions take effect in future sessions (processes), so in order to define the variable for the current process as well, run $env:FOO = 'bar' in addition, which is effectively the same as [Environment]::SetEnvironmentVariable('FOO', 'bar', 'Process').

[Environment]::SetEnvironmentVariable()UserMachine一起使用时,

When using [Environment]::SetEnvironmentVariable() with User or Machine, a WM_SETTINGCHANGE message is sent to other applications to notify them of the change (though few applications react to such notifications).
This doesn't apply when targeting Process (or when assigning to $env:FOO), because no other applications (processes) can see the variable anyway.

另请参见.

[*]在类似Unix的平台上,从.NET Core 3.1起

这篇关于如果不存在,如何在PowerShell中设置env变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆