Extract Paths from Strings Like Environment Variables

by May 29, 2012

If you'd like to add a path to the %PATH% environment variable, that's easy:

PS> $env:path += ''

But how would you remove a path? Here's a clever way:

PS> (($env:path -split '') -ne 'C:\Windows\system32') -join ';'

To better understand the technique used, check out this part first:

PS> $env:path -split ''

It will separate the paths in %PATH%. Next, -ne will return all paths that do not match the one you want to get rid of. Finally, -join adds these parts back to a semicolon-separated list.

Twitter This Tip! ReTweet this Tip!