Monday, June 11, 2012

Extract Paths from Strings Like Environment Variables

If you'd like to add a path to the %PATH% environment variable, that's easy:
PS$env:path += ';c: \newpath'
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.