Utilities
Utilities copied to clipboard
Set-PathVariable.ps1 suggestions
A few suggestions for Set-PathVariable.ps1:
-
The regex on line 45 should end with a
$to avoid a partial match.From:
$arrPath = $arrPath | Where-Object { $_ -notMatch "^$path\\?" }To:
$arrPath = $arrPath | Where-Object { $_ -notMatch "^$path\\?$" }Otherwise,
Set-PathVariable -RemovePath 'C:\Temp'could incorrectly remove a path such asC:\Temp2. -
The
-joincommand on line 47 may leave an empty array element, creating a trailing semi-colon in the PATH:PS> $env:Path C:\Windows;C:\Windows\System32;C:\Temp PS> Set-PathVariable -RemovePath 'C:\Temp' PS> $env:Path C:\Windows;C:\Windows\System32;Change from:
$value = ($arrPath + $addPath) -join ';'To:
$value = ($arrPath + $AddPath | Where { $_ }) -join ';'The
| Where { $_ }will remove empty/null elements, avoiding this problem:PS> $env:Path C:\Windows;C:\Windows\System32;C:\Temp PS> Set-PathVariable -RemovePath 'C:\Temp' PS> $env:Path C:\Windows;C:\Windows\System32 -
In addition to the above, using
Group-Objectcould be a convenient way to remove duplicates:$value = ($arrPath + $AddPath | Where { $_ } | Group-Object).Name -join ';'Example (note the additional
C:\Windowsas well as a trailing;):PS> $env:Path C:\Windows;C:\Windows\System32;C:\Temp;C:\Windows; PS> Set-PathVariable -RemovePath 'C:\Temp' PS> $env:Path C:\Windows;C:\Windows\System32