-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Add-Path.ps1
69 lines (55 loc) · 1.36 KB
/
Add-Path.ps1
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<#
.Synopsis
Adds a directory to an environment path variable.
Author: Roman Kuzmin
.Description
The script resolves the specified path, checks that the directory exists,
and adds the path to an environment variable if it is not there yet. The
changes are effective for the current process.
.Parameter Path
Specifies the path to be added.
Default is the current location.
.Parameter Name
Specifies the environment variable to be updated.
Default is 'PATH'.
.Inputs
None
.Outputs
None
.Example
> Add-Path
Adds the current location to the system path.
.Example
> Add-Path TestModules PSModulePath
Adds TestModules to the PowerShell module path.
.Link
https://github.com/nightroman/PowerShelf
#>
param(
[Parameter()]
[string[]]$Path = '.',
[string]$Name = 'PATH'
)
function Add-Path($Path) {
# resolve and check
$Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
if (![System.IO.Directory]::Exists($Path)) { Write-Error "Missing directory '$Path'." -ErrorAction Stop }
# already added?
$var = [Environment]::GetEnvironmentVariable($Name)
$trimmed = $Path.TrimEnd('\')
foreach($dir in $var.Split(';')) {
if ($dir.TrimEnd('\') -eq $trimmed) {
return
}
}
# add the path
[Environment]::SetEnvironmentVariable($Name, $Path + ';' + $var)
}
try {
foreach($Path in $Path) {
Add-Path $Path
}
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}