Handy PowerShell script for tweaking $env:PATH

Anyone who has worked with me knows I’m a bit of a command-line junkie. Lately, I’ve been setting up a test environment with lots of servers. I want to be able to use my favourite command line utils from the prompt, and since this is a Microsoft Windows environment, that means PowerShell. Today I found myself installing some utils then adding the newly installed locations to the PATH environment variable. After the first machine, and facing the prospect of several more, I decided to cruft up something that would work from within PowerShell and keep me away from that nasty GUI stuff. (Computer-Properties-Advanced System Settings-Environment Variables-Path-Edit-DearLordThereMustBeABetterWay…)

And so here’s what I came up with: Add-Path.ps1. You feed it a path name, it checks to make sure it is a valid path, and if so, adds it to the PATH environment variable. You can either add it just for the current session, or use the -Peristent switch to make the change stick.

Add-Path.ps1

param([string]$pathName,[switch]$Persistent=$false)

if ($pathName)
{
    if (Test-Path $pathName)
    {
        if ($env:PATH.IndexOf($pathName) -gt -1)
        {
            Write-Host "$pathName is already on the path"
        }
        else
        {
            Write-Host "Going to add $pathName to the path"
            $newPath = "$env:Path;$pathName"
            if ($Persistent)
            {
                # update the registry and add the path
                # NB, you'll need admin creds for the reg change
                [System.Environment]::SetEnvironmentVariable("PATH", $newPath, "Machine")
                $env:Path = $newPath
            }
            else
            {
                # just add the path for this session
                $env:Path = $newPath
            }

            Write-Host "Path is now: [$newPath]"
        }
    }
    else
    {
        Write-Host "Path does not exist"
    }
}
else
{
    Write-Host "Need a path name to add"
}