Skip to content

Instantly share code, notes, and snippets.

@ImIOImI
Created July 29, 2020 22:21
Show Gist options
  • Save ImIOImI/df15aed37ada657809e20cf1dae436a9 to your computer and use it in GitHub Desktop.
Save ImIOImI/df15aed37ada657809e20cf1dae436a9 to your computer and use it in GitHub Desktop.
Adds a given folder to the windows path.
#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