How to remove duplicates from the Path environment variable with PowerShell

Sometimes you discover that there are many duplicates in your Path environment variable. This happens because most of the software you install just add new paths without formerly checking if they already exist.

How to do it with Powershell

First, we want to get the current content of the Path environment variable.

$CurrentPath = [Environment]::GetEnvironmentVariable('Path','Machine')

Now we want to split this whole string into an array of paths.

$SplittedPath = $CurrentPath -split ';'

We can then remove all duplicate elements with the -Unique parameter of either the Select-Object or the Sort-Object cmdlet. Personally, I find it more interesting in this case to use the Sort-Object cmdlet. However, it doesn’t really matter, if this list is unsorted.

$CleanedPath = $SplittedPath | Sort-Object -Unique

Now we want to join everything together and make a unique whole string again.

$NewPath = $CleanedPath -join ';'

And last step is to set the Path environment variable with new value.

[Environment]::SetEnvironmentVariable('Path', $NewPath,'Machine')

Onliner bonus

If you are fan of oneliners, here is a possibility

[Environment]::SetEnvironmentVariable('Path',(([Environment]::GetEnvironmentVariable('Path','Machine') -split ';'|Sort-Object -Unique) -join ';'),'Machine')

And don’t forget

All currently running processes are still using the old value of the Path environment variable. Thus it is better to close everything and reopen it again, or just logoff and logon again.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s