windows Powershell 添加系统变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32730544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:16:53  来源:igfitidea点击:

Powershell Add System Variable

windowspowershellenvironment-variables

提问by Tyler S

I am Trying To add a System Variable here using PowerShell:

我正在尝试使用 PowerShell 在此处添加系统变量:

Environment Var dialog

环境变量对话框

I have tried both ways using

我已经尝试了两种方式使用

$env:MyTestVariable = "My test variable."

and

[Environment]::SetEnvironmentVariable("TestVariableName", "My Value", "<option>")

However neither of them seem to add to this section. I have tried restarting the computer as well to see if it would take effect then. I have looked at technet along with countless other websites, but nothing I have tried has worked.

但是,它们似乎都没有添加到本节中。我也尝试过重新启动计算机,看看它是否会生效。我已经查看了 technet 和无数其他网站,但我尝试过的一切都没有奏效。

How can I set a system variable with PowerShell?

如何使用 PowerShell 设置系统变量?

回答by TessellatingHeckler

Run PowerShell as an administrator (to get the necessary registry access permissions) then call out to the .Net framework to set it:

以管理员身份运行 PowerShell(以获得必要的注册表访问权限),然后调用 .Net 框架进行设置:

[Environment]::SetEnvironmentVariable("MyTestVariable", "MyTestValue", "Machine")

NB. it won't take effect within the same process, you'll have to make a new PowerShell process to see it.

注意。它不会在同一进程中生效,您必须创建一个新的 PowerShell 进程才能看到它。

回答by Gaspare Bonventre

Run PowerShell as an admin. Don't use this if you are trying to modify something like environmental extensions or environmental paths. No need to run refreshEnv and no need to open a new PowerShell window to see it

以管理员身份运行 PowerShell。如果您尝试修改诸如环境扩展或环境路径之类的内容,请不要使用它。无需运行 refreshEnv 也无需打开新的 PowerShell 窗口即可查看

$variableNameToAdd = "mytestVariableName"
$variableValueToAdd = "some environmental value to add"
[System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::Process)
[System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::User)

回答by NIK