54

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?

CJBS
  • 14,479
  • 5
  • 82
  • 129
Tyler S
  • 777
  • 1
  • 11
  • 22
  • 4
    `[System.Environment]::SetEnvironmentVariable('name','value',[System.EnvironmentVariableTarget]::Machine)` – user4003407 Sep 23 '15 at 03:40
  • possible duplicate of [Powershell - changing the value of an environment variable](http://stackoverflow.com/questions/15261431/powershell-changing-the-value-of-an-environment-variable) – user4003407 Sep 23 '15 at 03:46

3 Answers3

77

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.

TessellatingHeckler
  • 24,312
  • 4
  • 40
  • 77
16

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)
Gaspare Bonventre
  • 1,014
  • 9
  • 18
3

You can find a cool explanation of this below,

https://trevorsullivan.net/2016/07/25/powershell-environment-variables/

NIK
  • 869
  • 9
  • 17
  • Link is not working, do you have some spare? – JorgeM Jan 19 '22 at 16:14
  • Working archived link: https://web.archive.org/web/20210228001104/https://trevorsullivan.net/2016/07/25/powershell-environment-variables/ – JWCS Feb 23 '22 at 21:51