Skip to content

Instantly share code, notes, and snippets.

@mhudasch
Last active September 27, 2016 14:41
Show Gist options
  • Save mhudasch/9f1fd26de6d105cd1a5482e4a33ed18e to your computer and use it in GitHub Desktop.
Save mhudasch/9f1fd26de6d105cd1a5482e4a33ed18e to your computer and use it in GitHub Desktop.
Add a path to the machine PATH environment variable
Function Add-EnvironmentPath {
<#
.SYNOPSIS
Adds a path to the PATH environment variable at give scope.
.DESCRIPTION
Adds a Path to the PATH environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.
In addition to that the command sorts the paths and removes duplicates.
.PARAMETER Path
The path to the PATH environment variable.
.PARAMETER scope
The scope which decides where to extend the PATH environment variable.
.EXAMPLE
Add-EnvironmentPath -Path "C:\WINDOWS\System32\WindowsPowerShell\v1.0\"
Since the default value for the parameter Scope is 'Machine' the path will be added to the PATH environment variable stored in 'HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment'.
.EXAMPLE
Add-EnvironmentPath -Path "C:\WINDOWS\System32\WindowsPowerShell\v1.0\" -Scope User
Adds the given path to the environment variable stored in 'HKEY_CURRENT_USER\Environment'
.EXAMPLE
Add-EnvironmentPath -Path "C:\WINDOWS\System32\WindowsPowerShell\v1.0\" -Scope Process
Adds the given path to $env:PATH of the current process.
#>
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string]$Path,
[Parameter(Mandatory=$false,Position=1)]
[ValidateSet("Process", "User", "Machine")]
[string]$Scope = "Machine")
Process {
$currentPaths = [System.Environment]::GetEnvironmentVariable("Path", $Scope)
if ($currentPaths.indexOf($Path) -eq -1) {
Write-Output "Updating PATH to include $Path`r`n"
$paths = @(($currentPaths.Split(";") | ForEach-Object { $_.Trim(); } | Where-Object { -not([string]::IsNullOrWhiteSpace($_)) }) | Sort-Object);
$paths += $Path;
$new = [string]::Join(";", @($paths | Select-Object -Unique | Sort-Object));
[System.Environment]::SetEnvironmentVariable("Path", $new, $Scope);
([string](refreshenv)) | Write-Output;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment