2

Good afternoon all;

I am attempting to remove multiple entries from the system path for a number of computers. Specifically, c:\program files\pythonx; c:\program files\pythonx\scripts for multiple versions of python.

What I am unable to do is actually parse this information out and re-apply it while keeping the remainder of the paths within the variable itself. As Such, I have gone to what I thought would be a more simple process and exported the path to a text file and then searched the text file for said values. I cannot, regardless of what I try, get the script to output a new file minus the values I want removed. I am sure that it is a problem escaping the space character in the paths but I'm unsure how to proceed. Any help would be very appreciated.

Example code:

    $1 = "c:\program files\python310"
    $2 = "c:\program files\python310\scripts"
    get-content c:\temp\test.txt | where-Object {$_ -notmatch [regex]::Escape($1) -or $_ -notmatch   [regex]::Escape($2) }| Set-Content c:\temp\test2.txt

path1 is just outputting the path on separate lines 1 is the first string I want to search for 2 is the second string I want to search for

I have also tried triple quotes in the $1 & $2 variables.

RJC
  • 21
  • 1
  • As an aside: while variable names such as `$1` are technically valid, it's best to avoid them, both for how nondescript they are and for the fact that they wouldn't (fully) work as _parameter_ variables - see [GItHub issue #19580](https://github.com/PowerShell/PowerShell/issues/19580). – mklement0 Jun 01 '23 at 01:54

1 Answers1

0

Your immediate problem is a logic error: replace -or with -and - otherwise, all lines by definition match.

However, you don't need to use files to remove $env:PATH entries. Try the following:

# Note: On Unix, use ':' instead of ';', or, for cross-platform use, 
#       [IO.Path]::PathSeparator
$modifiedPath = 
  $env:PATH -split ';' -ne 'c:\program files\python310' `
                       -ne 'c:\program files\python310\scripts' `
                       -join ';'
  • -split is used to split the string into an array of entries.

  • -ne, with an array as its LHS acts as a filter, returning a sub-array of (non-)matching items.

  • -join is used to join the elements of the filtered array to form a single string again.

Caveat:

  • See mclayton's comments below for potential edge cases.
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Note that while splitting on ```;``` will work 99.9% of the time (or more) in practice, there are some edge cases where a directory name may contain a ```;``` inside a quoted string - see https://stackoverflow.com/a/73255509/3156906, and there are loads of other exceptions as well, listed pretty comprehensively here: https://stackoverflow.com/questions/141344/how-to-check-if-a-directory-exists-in-path/8046515#8046515 – mclayton May 31 '23 at 14:23