65

I am Trying To add a System Variable here using 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.

How can I set a system variable with PowerShell?

4

3 Answers 3

96

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

[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.

Sign up to request clarification or add additional context in comments.

3 Comments

About the NB: if you have choco installed, you can run refreshenv to use the same powershell process ;)
You have to use that that third parameter ('Machine') to achieve what the original poster is attempting.
As @gaspare Bonventre mention in its answer, it is better to use [System.EnvironmentVariableTarget]::Machine instead of "Machine" as third parameter
24

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

$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)

Comments

4

You can find a cool explanation of this below,

https://web.archive.org/web/20210228001104/https://trevorsullivan.net/2016/07/25/powershell-environment-variables/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.