MyITGuy
4/6/2016 - 6:14 PM

PowerShell: Repair PATH System Variable

PowerShell: Repair PATH System Variable

$MandatoryOrderedPaths = @(
    "$($env:SystemRoot)\System32"
    "$($env:SystemRoot)"
    "$($env:SystemRoot)\System32\Wbem"
    "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\"
    "$($env:SystemRoot)\SysWOW64"
    "$($env:SystemRoot)\SysWOW64\Wbem"
    "$($env:SystemRoot)\SysWOW64\WindowsPowerShell\v1.0\"
)
# Remove trailing slash in paths
$MandatoryOrderedPaths = $MandatoryOrderedPaths | % {$_.Trimend('\')}
# Get current PATH
$CurrentPaths = $env:PATH -split(';')
# Remove trailing slash in paths
$CurrentPaths = $CurrentPaths | % {$_.Trimend('\')}
# Unique
$CurrentPaths = $CurrentPaths | Sort -Unique
# Path exists
$CurrentPaths = $CurrentPaths | ? {$_} | ? {Test-Path -Path $_ -PathType Container -ErrorAction SilentlyContinue}
# Remove Mandatory from Current
$CurrentPaths = $CurrentPaths | ? {$MandatoryOrderedPaths -notcontains $_}
# Show new PATH
"$($MandatoryOrderedPaths -join ';');$($CurrentPaths -join ';')"
[Environment]::SetEnvironmentVariable("PATH", "$($MandatoryOrderedPaths -join ';');$($CurrentPaths -join ';')", "MACHINE")