Setting (And Deleting) Environment Variables

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

PowerShell can read environment variables easily. This returns the current windows folder:

$env:windir

However, if you want to make permanent changes to user or machine environment variables, you need to access .NET functionality. Here is a simple function that makes setting or deleting environment variables a snap:

function Set-EnvironmentVariable
{
    param
    (
        [Parameter(Mandatory=$true, HelpMessage='Help note')]
        $Name,

        [System.EnvironmentVariableTarget]
        $Target,

        $Value = $null

    )
    
    [System.Environment]::SetEnvironmentVariable($Name, $Value, $Target )

} 

To create a permanent user environment variable, try this:

Note that new user variables are visible only to newly launched applications. Applications that were already running will keep their copied process set unless they explicitly ask for changed variables.

And here is the line that deletes the variable again:

Twitter This Tip! ReTweet this Tip!


Posted Feb 07 2014, 06:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.