Private/Path/Remove-Path.ps1
<# .SYNOPSIS Removes a path from the PATH environmental variable. .PARAMETER Path Path to remove. .PARAMETER EnvironmentVariableTarget Environmental variable target (scope). #> Function Remove-Path { [CmdletBinding(SupportsShouldProcess = $true)] Param( [Parameter(Position = 1, Mandatory = $true, ValueFromPipeline = $true, HelpMessage = "Path to be added")] [string]$Path , [Parameter(Position = 2, HelpMessage = "Environmental variable target")] [ValidateSet("Machine", "Process", "User")] [Alias("Target")] [string]$EnvironmentVariableTarget = [EnvironmentVariableTarget]::Machine ) Begin { $currentPath = [Environment]::GetEnvironmentVariable("Path", $EnvironmentVariableTarget) } Process { If ($PSCmdlet.ShouldProcess($Path, "Remove from `$env:PATH in $($EnvironmentVariableTarget) scope")) { $pathSeparator = [System.IO.Path]::PathSeparator $paths = $currentPath -split $pathSeparator | Where-Object { !([string]::IsNullOrWhiteSpace($_)) } If ($paths -contains $Path) { $paths = $paths | Where-Object { $_ -ne $Path } $newPath = $paths -join $pathSeparator If ($newPath -ne $currentPath) { [Environment]::SetEnvironmentVariable("Path", $newPath, $EnvironmentVariableTarget) } } } } End { $env:Path = [Environment]::GetEnvironmentVariable("Path", $EnvironmentVariableTarget) } } |