Created
April 15, 2022 19:46
-
-
Save BCSharp/4de8b182aac44be7d0b18cc1c9866080 to your computer and use it in GitHub Desktop.
PowerShell function to add a path to the PATH environment variable
This file contains hidden or 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
<# | |
.Synopsis | |
Add a path to the PATH environment variable. | |
.Description | |
Adds the given path to the paths defined in the PATH environment variable. | |
The path is only added if it is not already in PATH and it actually resolves to an existing directory. | |
Empty paths (empty strings) are not added and any empty paths in PATH are removed. Add '.' to refer to the current directory. | |
.Parameter Path | |
The path to be added. It is being tested if it leads to an existing object. If not, it is not added. | |
.Parameter Prepend | |
Add the path to the beginning of paths listed in PATH. By default, paths are added at the end. | |
.Parameter Category | |
The PATH variable category to modify. An empty (default) category denotes env:PATH. A non-empty category denotes an environment PATH variable which name starts with the given category. E.g. category MAN denotes env:MANPATH. | |
#> | |
function Add-EnvPath { | |
param( | |
[Parameter(Mandatory=$true)] | |
[string] $Path, | |
[Parameter(Mandatory=$false)] | |
[Switch] $Prepend, | |
[Parameter(Mandatory=$false)] | |
[string] $Category | |
) | |
if (Test-Path -Path $Path) { | |
if (Test-Path -Path Env:${Category}PATH) { | |
$envPaths = (Get-Content -Path Env:${Category}PATH) -split [IO.Path]::PathSeparator | |
} else { | |
$envPaths = @() | |
} | |
if ($envPaths -notcontains $Path) { | |
if ($Prepend) { | |
$envPaths = ,$Path + $envPaths | where { $_ } | |
} else { | |
$envPaths = $envPaths + $Path | where { $_ } | |
} | |
Set-Content -Path Env:${Category}PATH -Value ($envPaths -join [IO.Path]::PathSeparator) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment