Powershell function to add system path
Was automating some installs and noted that powershell does not have a built-in function to add path to the system path.
It was an easy fix - just use [System.Environment]::SetEnvironmentVariable function.
function AddSystemPaths([array] $PathsToAdd) {
$VerifiedPathsToAdd = ""
foreach ($Path in $PathsToAdd) {
if ($Env:Path -like "*$Path*") {
echo " Path to $Path already added"
}
else {
$VerifiedPathsToAdd += ";$Path";echo " Path to $Path needs to be added"
}
}
if ($VerifiedPathsToAdd -ne "") {
echo "Adding paths: $VerifiedPathsToAdd"
[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + "$VerifiedPathsToAdd","Machine")
echo "Note: The new path does NOT take immediately in running processes. Only new processes will see new path."
}
}
Use example:
PS> AddSystemPaths ("C:\Program Files\sd","c:\tools")
Path to C:\Program Files\sd already added
Path to c:\tools needs to be added
Adding paths: ;c:\tools
Note: The new path does NOT take immediately in running processes. Only new processes will see new path.
PS>