问题描述
令我惊讶的是,在谷歌搜索了一段时间之后,没有得到这种常见情况的答案...
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会话时).
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).
在Windows 上,如果要持久地定义环境变量 ,则需要使用静态的方法的"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')
.
另请参见.
这篇关于如果不存在,如何在PowerShell中设置env变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!