Skip to content

Instantly share code, notes, and snippets.

@PSingletary
Created January 31, 2018 16:30
Show Gist options
  • Select an option

  • Save PSingletary/b8f2a8eed5956ce81cc6f31df01c00a2 to your computer and use it in GitHub Desktop.

Select an option

Save PSingletary/b8f2a8eed5956ce81cc6f31df01c00a2 to your computer and use it in GitHub Desktop.
Get-ENVPathFolders Function
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 [email protected] - Created
.Link http://blogs.catapultsystems.com/chsimmons/archive/2018/01/30/parse-envpath-with-powershell/
#>
$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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment