The environment variable PATH (combined SYSTEM PATH and USER PATH) can be tricky to parse if you want to check for each folder it contains.  This is due to the support of various formatting styles.  For example, this is a valid PATH statement:

C:\WINDOWS\;"C:\Path with semicolon; in the middle";"E:\Path with semicolon at the end;";;C:\Program Files;

Notice the differences

  • Folder with spaces
  • Folder without spaces
  • Folder with an ending backslash (\)
  • Folder without an ending backslash (\)
  • Folder with a semicolon in the middle
  • Folder with a semicolon at the end
  • Blank folder (;;)

A few references can be found…

But, I could find no simple method to parse this complexity so I wrote a PowerShell Function to handle it.

[read-more-redirect urltext=”CatapultSystems.com” url=”https://www.catapultsystems.com/blogs/parse-envpath-with-powershell”]

Function Get-ENVPathFolders {
     #.Synopsis Split $env:Path into an array
     #.Notes
     #  - Handle 1) folders ending in a backslash 2) double-quoted folders 3) folders with semicolons 4) folders with spaces 5) double-semicolons I.e. blanks
     #  - Example path: 'C:\WINDOWS\;"C:\Path with semicolon; in the middle";"E:\Path with semicolon at the end;";;C:\Program Files;'
     #  - 2018/01/30 by Chad@ChadsTech.net - Created
     $PathArray = @()
     $env:Path.ToString().TrimEnd(';') -split '(?=["])' | ForEach-Object { #remove a trailing semicolon from the path then split it into an array using a double-quote as the delimiter keeping the delimiter
         If ($_ -eq '";') { # throw away a blank line
         } ElseIf ($_.ToString().StartsWith('";')) { # if line starts with "; remove the "; and any trailing backslash
             $PathArray += ($_.ToString().TrimStart('";')).TrimEnd('\')
         } ElseIf ($_.ToString().StartsWith('"')) {  # if line starts with " remove the " and any trailing backslash
             $PathArray += ($_.ToString().TrimStart('"')).TrimEnd('\') #$_ + '"'
         } Else {                                    # split by semicolon and remove any trailing backslash
             $_.ToString().Split(';') | ForEach-Object { If ($_.Length -gt 0) { $PathArray += $_.TrimEnd('\') } }
         }
     }
     Return $PathArray
}

To prove it out

#output the array of PATH folders
Get-ENVPathFolders

#create a test file in half of the folders
$myFile = 'Test.file'
$i=0; Get-ENVPathFolders | ForEach-Object { $i++; If ($i%2 -eq 0) { New-Item -Path "$_" -Name $myFile -ItemType File } }

#output the PATH folders with the test file
Get-ENVPathFolders | ForEach-Object { If (Test-Path -Path $_\$myFile) { Write-Output "Found [$_\$myFile]" } }

Happy coding!

[/read-more-redirect]

Parse env:Path with PowerShell
Tagged on: