Setting Permanent Environment Variables

by Dec 3, 2015

When you set or change environment variables in PowerShell, this only affects the process set, so changes apply only to the current PowerShell session.

To set Windows environment variables permanently, use a function like this:

#requires -Version 2

function Set-EnvironmentVariable
{
  param
  (
    [Parameter(Mandatory=$true)]
    [String]
    $Name,
    
    [Parameter(Mandatory=$true)]
    [String]
    $Value,
    
    [Parameter(Mandatory=$true)]
    [EnvironmentVariableTarget]
    $Target
  )
  [System.Environment]::SetEnvironmentVariable($Name, $Value, $Target)
}

And this would create a new environment variable called "Test", with the value "Hello World", for the current user:

Set-EnvironmentVariable -Name test -Value 'Hello World' -Target User 

Note that you will not see the new variable in the current PowerShell env: drive. It is visible in all newly launched applications including newly launched PowerShell, but you could check its existence like this even within the PowerShell that created the variable:

 
PS> [Environment]::GetEnvironmentVariable('test', 'User')
Hello World
 

This call bypasses the process set of environment variables (the copy of environment variables a process receives when it starts).

Twitter This Tip! ReTweet this Tip!