Manipulating your PATH variable using Powershell

The PATH variable in windows is something you occasionally have to touch.

The classic command for manipulating PATH is simply

set PATH=%PATH%;x:\your\folder\here

Now this does the trick, and you don’t have to do a lot of work to get powershell to do the same thing, the command is simply

$env:Path = $env:Path+";x:\your\folder\here"

The only problem is that the $env:Path variable is only a temporary variable that is available in your current session. This won’t do if you want to make your changes persistent. In addition, I found making the PATH variable a bit more readable helped when dealing with it.

What we will be doing is leveraging the setx command to make the changes permanent.

 

function get-path
{
    $env:Path -split (";")
}

function add-path($folder)
{
    $addtopath = ";"+$folder
    $env:Path = $env:Path + $addtopath
    $setpath = "setx Path ""$env:Path"" -m"
    Invoke-Expression $setpath
}

function remove-path($folder)
{
    $removepath = ";"+$folder
    $env:Path = $env:Path.Replace($removepath,$NULL)
    $setpath = "setx Path ""$env:Path"" -m"
    Invoke-Expression  $setpath
}

This is the simplest way I could come up with for editing the path variable through powershell and making the changes permanent. This module will throw an error if you don’t have administrative privileges, as those are required for editing the registry, however even in a non-elevated session it will still change your local path variable for that session.

get-path simply displays the path variable in your current session in a comfortable way.

There is a more elegant way of doing this, but I like the simplicity of this one. If you’re looking for a pure powershell implementation though, here’s a link to a great article on Technet

http://blogs.technet.com/b/heyscriptingguy/archive/2011/07/23/use-powershell-to-modify-your-environmental-path.aspx

Advertisements
Tagged with: , , ,
Posted in Uncategorized
One comment on “Manipulating your PATH variable using Powershell
  1. […] I always keep a handy c:tools folder on my windows machines, and I add it to the path of the machine, so I can tab-complete and call the programs in there from wherever I am. Another option is sticking the portcheck.exe file in a directory that is included in the path by default, such as c:windows. I highly recommend the tools approach though. Here’s an older article on how to add stuff to your path quickly. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: