Utilities icon indicating copy to clipboard operation
Utilities copied to clipboard

Set-PathVariable.ps1 suggestions

Open OnlineCop opened this issue 2 years ago • 0 comments

A few suggestions for Set-PathVariable.ps1:

  1. 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 as C:\Temp2.

  2. The -join command 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
    
  3. In addition to the above, using Group-Object could be a convenient way to remove duplicates:

        $value = ($arrPath + $AddPath | Where { $_ } | Group-Object).Name -join ';'
    

    Example (note the additional C:\Windows as 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
    

OnlineCop avatar May 26 '23 20:05 OnlineCop