-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModifyUserPath.ps1
More file actions
54 lines (43 loc) · 1.68 KB
/
ModifyUserPath.ps1
File metadata and controls
54 lines (43 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# PowerShell 7 Script to Add or Remove a Path from User's Environment Variable
param (
[string]$PathToModify = "$HOME\Bin",
[switch]$Remove
)
function Add-PathToUserProfile {
param (
[string]$Path
)
# Getting the current path environment variable
$currentPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::User)
# Check if the path already exists in the environment variable
if ($currentPath -like "*$Path*") {
Write-Host "Path $Path already exists in user environment variable."
} else {
# Adding the new path
$newPath = $currentPath + ";" + $Path
[Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::User)
Write-Host "Path $Path added to user environment variable."
}
}
function Remove-PathFromUserProfile {
param (
[string]$Path
)
# Getting the current path environment variable
$currentPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::User)
# Check if the path exists in the environment variable
if ($currentPath -like "*$Path*") {
# Removing the path
$newPath = ($currentPath -split ';' | Where-Object { $_ -ne $Path }) -join ';'
[Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::User)
Write-Host "Path $Path removed from user environment variable."
} else {
Write-Host "Path $Path does not exist in user environment variable."
}
}
# Modify the PATH based on the command line option
if ($Remove) {
Remove-PathFromUserProfile -Path $PathToModify
} else {
Add-PathToUserProfile -Path $PathToModify
}