Setting Environment Variables

by Dec 29, 2017

PowerShell can set environment variables only in its process set, so these changes will not persist and are not visible outside of PowerShell.

To permanently set environment variables, here is a simple function:

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

This is how you can set environment variables now:

 PS> Set-EnvironmentVariable -Name test -Value 123 -Target User 

You can also remove environment variables by submitting an empty string as value:

 PS> Set-EnvironmentVariable -Name test -Value "" -Target User 

This is why the -Value parameter was declared with the [AllowEmptyString()] attribute; without this attribute, a mandatory parameter cannot receive an empty string, thus without this attribute, the function would not have been able to remove environment variables.

Another noteworthy part is the type declaration for the -Target parameter: because an enumeration type was specified, when you use this function in the PowerShell ISE or another editor with IntelliSense, the editor will conveniently provide IntelliSense choices.

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this years’ PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at

Twitter This Tip! ReTweet this Tip!