Skip to content

Instantly share code, notes, and snippets.

@AdilHindistan
Created November 20, 2015 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdilHindistan/e5bf58ce4a8ce5d1a7c5 to your computer and use it in GitHub Desktop.
Save AdilHindistan/e5bf58ce4a8ce5d1a7c5 to your computer and use it in GitHub Desktop.
PowerShell Function to Fix System Path by removing duplicates
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