Edit (Add / Remove) System Path Variable via PowerShell

Ok, so I found a ton of blogs / posts out there about changing the System Path Variable in Windows, but not a way I’d want to do it, so I came up with my own script for adding / removing items.

What it does.

  • Grabs Current System Environment Path Variable and Places into a PowerShell Variable “Environment”
  • Checks for “rules” of items you want to delete, then deletes them from the PowerShell Variable
  • Adds any “Additional Items” you specify into the PowerShell Variable
  • Commits the PowerShell Variable “Environment” as the Updated System Path Variable.

In Action: (Please Note, the added and removed items are ONLY for example, I’m NOT suggesting you do this)



#Script to Add and/or remove items from the System Path

#Get Current Path
$Environment = [System.Environment]::GetEnvironmentVariable("Path", "Machine")

#Remove "Junk" from Path
foreach ($path in ($Environment).Split(";"))
    if ($path -like "*SysWOW64\WIndowsPowerShell\v1.0*")
        $Environment = $Environment.Replace($Path ,"")
    if ($path -like "c:\temp*")
        $Environment = $Environment.Replace($Path ,"")

#Add Items to Environment
$AddPathItems = "C:\Windows\CCM\;C:\ProgramData\WaaS\;"
$Environment = $Environment.Insert($Environment.Length,$AddPathItems)

#Set Updated Path
[System.Environment]::SetEnvironmentVariable("Path", $Environment, "Machine")

Posted Originally on GARYTOWN.COM

1 thought on “Edit (Add / Remove) System Path Variable via PowerShell”

  1. This is a great post. Keep up the good work. I’ve used it for reference to start my own script using your method, but with a little modification to your original. Please don’t mind.
    The section that I’ve changed on my below and the reason for it. I’ve found that in the original script because you’re adding a semicolon “;” along with the string you want to add, when you remove it using the same code during an uninstall per say, it leaves the semicolon behind. So, your path ends with something like this ;; with multiple semicolons at the end of it when you remove the new path you’ve just added. Which is okay, it doesn’t affect the way it works, but this makes it a little cleaner.
    #Add Items to Environment, split into array, create a new array so that you can add to it, rejoin it and use that as the final path to set
    $newpath = $Environment.Split(“;”)
    [System.Collections.ArrayList]$AddNewPathList = $newpath
    $AddNewPathList.Add(“C:\Program Files\MyNewProgram”)
    $FinalPath = $AddNewPathList -join “;”

    #Set Updated Path
    [System.Environment]::SetEnvironmentVariable(“Path”, $FinalPath, “Machine”)


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.