Created
May 24, 2023 21:39
-
-
Save markcastle/85795d9224e3489ac277d2dfb5819bcc to your computer and use it in GitHub Desktop.
Powershell script to remove a directory from the PATH on Windows (for either System or User) with optional 'Dry Run' mode
This file contains 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
# Powershell script to remove a directory from the PATH on Windows for either System or User | |
# Can optionally run it in dry run mode to be certain it's going to do what you require | |
# | |
# Specify the target (User or Machine), dry run mode, and directory to remove | |
# Examples | |
# .\remove_from_path.ps1 -DirectoryToRemove "C:\Path\To\Directory" | |
# This will remove C:\Path\To\Directory from the user PATH. | |
# | |
# .\remove_from_path.ps1 -DirectoryToRemove "C:\Path\To\Directory" -Target Machine | |
# This will remove C:\Path\To\Directory from the system PATH. | |
# | |
# You can also specify the DryRun parameter to see what changes the script would make without actually making them: | |
# .\remove_from_path.ps1 -DirectoryToRemove "C:\Path\To\Directory" -DryRun true | |
# | |
param( | |
[Parameter(Mandatory=$false)] | |
[ValidateSet("User", "Machine")] | |
[string]$Target = "User", | |
[Parameter(Mandatory=$false)] | |
[ValidateSet("true", "false")] | |
[string]$DryRun = "false", | |
[Parameter(Mandatory=$true)] | |
[string]$DirectoryToRemove | |
) | |
# Get the current PATH | |
$path = [Environment]::GetEnvironmentVariable('Path', $Target) | |
# Split the PATH into an array of directories | |
$directories = $path -split ';' | |
# Check if the directory to remove is in the PATH | |
if ($DirectoryToRemove -in $directories) { | |
# Remove the directory from the array | |
$newDirectories = $directories -ne $DirectoryToRemove | |
if ($DryRun -eq "true") { | |
# Dry run: show what would be done | |
Write-Host "Dry Run: would remove $DirectoryToRemove from the $Target PATH." | |
Write-Host "New PATH would be: `n$(($newDirectories -join ';'))" | |
} else { | |
# Set the new PATH | |
[Environment]::SetEnvironmentVariable('Path', ($newDirectories -join ';'), $Target) | |
Write-Host "$DirectoryToRemove removed from the $Target PATH." | |
} | |
} else { | |
Write-Host "$DirectoryToRemove is not in the $Target PATH." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to add PATH from
ps1