Last active
July 10, 2023 07:16
-
-
Save mavaddat/34ffda58ac156ff37468a70179f0cae3 to your computer and use it in GitHub Desktop.
Reverse resolve %PATH% paths using available environment variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a list of the environment variables sorted by length | |
$envs = Get-ChildItem -Path Env:\ | ForEach-Object { | |
[pscustomobject]@{ | |
Length = $_.Value.Length | |
Name = $_.Name | |
Value = $_.Value | |
} | |
} | Sort-Object -Descending -Property Length | |
# Replace the environment variables in the user path with the variable name | |
$userPath = [System.Environment]::GetEnvironmentVariable('PATH',[System.EnvironmentVariableTarget]::User) -split [System.IO.Path]::PathSeparator | |
$revertedPath = New-Object -TypeName "pscustomobject[]" -ArgumentList ($userPath.Count) | |
for($i=0; $i -lt $userPath.Count; $i++) { | |
$revertedPath[$i] = [pscustomobject]@{ Before = $userPath[$i]; After = $null } | |
foreach($env in $envs){ | |
$env.Value = $env.Value -replace '\\$' | |
$userPath[$i] = $userPath[$i] -replace "^$([regex]::Escape(($env.Value)))", ('$env:' + $env.Name) } | |
} | |
$revertedPath[$i].After = $userPath[$i] | |
} | |
# Print out the results | |
$revertedPath | Format-Table -AutoSize -Wrap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment