Skip to content

Set-PathVariable.ps1 suggestions #7

@OnlineCop

Description

@OnlineCop

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions