Created
November 20, 2015 17:50
-
-
Save AdilHindistan/e5bf58ce4a8ce5d1a7c5 to your computer and use it in GitHub Desktop.
PowerShell Function to Fix System Path by removing duplicates
This file contains 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
Function Fix-SystemPath { | |
<# | |
.SYNOPSIS | |
Fixes System Path | |
.DESCRIPTION | |
Removes duplicates from System Path | |
#> | |
[CMDLETBINDING(SupportsShouldProcess)] | |
param( | |
$OutputFile=$("${env:TEMP}\${env:ComputerName}_FixedPath.csv") | |
) | |
$EnvVarRegPath = 'HKLM:\System\currentcontrolset\control\session manager\environment\' | |
$CurrentPath = (Get-ItemProperty -Path $EnvVarRegPath -Name Path).path | |
# Following would work but would also change the order of path; not ideal! | |
#$FixedPath=($CurrentPath -split ';' |where {$_ -ne ''} |sort -Unique) -join ';' | |
# We will keep the order as is! | |
$arr=@() | |
$CurrentPath -split ';' |where {$_ -ne ''} | % { | |
if (!$arr.Contains($_)) { | |
$arr += $_ | |
} | |
} | |
$FixedPath = $arr -join ';' | |
$PathFixed=$false | |
$NeedFix=$false | |
If ($CurrentPath.Length -gt $FixedPath.Length ) { | |
$NeedFix=$true | |
Try | |
{ | |
If ($PSCMDLET.ShouldProcess($env:ComputerName,'Update System Path')){ | |
Write-Verbose "Updating System Path" | |
Set-ItemProperty $EnvVarRegPath -Name Path -Value $FixedPath -PassThru -Force | |
$PathFixed=$true | |
} | |
} | |
catch | |
{ | |
$PathFixed=$false | |
} | |
} | |
$result = [PSCustomObject]@{ComputerName=$env:COMPUTERNAME;NeedFix=$NeedFix; IsFixed=$PathFixed;PathSizeCurrent=$($CurrentPath.Length);PathSizeFixed=$($FixedPath.Length);PathBefore=$CurrentPath;PathAfter=$FixedPath} | |
$result | export-csv -NoTypeInformation -Path $outputFile -Force | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment