Created
July 29, 2020 22:21
-
-
Save ImIOImI/df15aed37ada657809e20cf1dae436a9 to your computer and use it in GitHub Desktop.
Adds a given folder to the windows path.
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
#Requires -RunAsAdministrator | |
param ( | |
[Parameter(Mandatory=$true)][string]$folder | |
) | |
if((Get-Item $folder) -is [System.IO.DirectoryInfo]) | |
{ | |
$folder = Resolve-Path $folder | |
} | |
else{ | |
Write-Host "Submitted value $folder is not a folder" | |
exit | |
} | |
Write-Host "Testing $folder to see if it's already in the path" -ForegroundColor Green | |
$regKey = ([Microsoft.Win32.Registry]::LocalMachine).OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", $True) | |
$oldpath = $regKey.GetValue("Path", $Null, "DoNotExpandEnvironmentNames") | |
$array = $oldpath.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries) | |
$NewValues = @() | |
ForEach ($Value in $array) | |
{ | |
if ($NewValues -notcontains $folder) | |
{ | |
$NewValues += $Value | |
} | |
else | |
{ | |
$IsDuplicate = $True | |
} | |
} | |
if ($IsDuplicate) | |
{ | |
Write-Host "Duplicate value found $folder already in path" -ForegroundColor Green | |
exit | |
} | |
else | |
{ | |
Write-Host "Adding new folder to path" -ForegroundColor Green | |
$NewValues += $folder | |
$NewValue = $NewValues -join ";" | |
$regKey.SetValue("Path", $NewValue, [Microsoft.Win32.RegistryValueKind]::ExpandString) | |
Write-Host "New PATH entry found and new PATH built removing all duplicates. New Path :" + $NewValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment