Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CLI: Adding paths to PATH environment variable in Windows
#!/usr/bin/env powershell
function Prepend-Idempotent {
# the delimiter is expected to be just 1 unique character
# otherwise there may be problems with trimming
param (
[string]$InputString,
[string]$OriginalString,
[string]$Delimiter = '',
[bool]$CaseSensitive = $false
)
if ($CaseSensitive -and ("$OriginalString" -cnotlike "*${InputString}*")) {
"$InputString".TrimEnd("$Delimiter") + "$Delimiter" + "$OriginalString".TrimStart("$Delimiter")
} elseif (! $CaseSensitive -and ("$OriginalString" -inotlike "*${InputString}*")) {
"$InputString".TrimEnd("$Delimiter") + "$Delimiter" + "$OriginalString".TrimStart("$Delimiter")
} else {
"$OriginalString"
}
}
function Append-Idempotent {
# the delimiter is expected to be just 1 unique character
# otherwise there may be problems with trimming
param (
[string]$InputString,
[string]$OriginalString,
[string]$Delimiter = '',
[bool]$CaseSensitive = $false
)
if ($CaseSensitive -and ("$OriginalString" -cnotlike "*${InputString}*")) {
"$OriginalString".TrimEnd("$Delimiter") + "$Delimiter" + "$InputString".TrimStart("$Delimiter")
} elseif (! $CaseSensitive -and ("$OriginalString" -inotlike "*${InputString}*")) {
"$OriginalString".TrimEnd("$Delimiter") + "$Delimiter" + "$InputString".TrimStart("$Delimiter")
} else {
"$OriginalString"
}
}
function Add-Path {
param (
[string]$NewPath,
[ValidateSet('Prepend','Append')]$Style = 'Prepend',
[ValidateSet('User', 'System')]$Target = 'User'
)
try {
# we need to do this to make sure not to expand the environment variables already inside the PATH
if ($Target -eq 'User') {
$Key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
} elseif ($Target -eq 'System') {
$Key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)
}
$Path = $Key.GetValue('Path', $null, 'DoNotExpandEnvironmentNames')
# note that system path can only expand system environment variables and vice versa for user environment variables
# in order to make sure this method is idempotent, we need to check if the new path already exists, this requires having a semicolon at the very end
if ($Style -eq 'Prepend') {
$key.SetValue('Path', (Prepend-Idempotent ("$NewPath".TrimEnd(';') + ';') ("$Path".TrimEnd(';') + ';') ';' $false), 'ExpandString')
} elseif ($Style -eq 'Append') {
$key.SetValue('Path', (Append-Idempotent ("$NewPath".TrimEnd(';') + ';') ("$Path".TrimEnd(';') + ';') ';' $false), 'ExpandString')
}
# update the path for the current process as well
$Env:Path = $key.GetValue('Path', $null)
} finally {
$key.Dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.