Powershell Add System Variable

WindowsPowershellEnvironment Variables

Windows Problem Overview


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?

Windows Solutions


Solution 1 - Windows

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.

Solution 2 - Windows

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)

Solution 3 - Windows

You can find a cool explanation of this below,

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTyler SView Question on Stackoverflow
Solution 1 - WindowsTessellatingHecklerView Answer on Stackoverflow
Solution 2 - WindowsGaspare BonventreView Answer on Stackoverflow
Solution 3 - WindowsNIKView Answer on Stackoverflow