-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Set-Env.ps1
60 lines (49 loc) · 1.61 KB
/
Set-Env.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
<#
.Synopsis
Sets or removes environment variables (Windows User/Machine).
Author: Roman Kuzmin
.Description
This command sets or removes the current User or local Machine environment
variable and updates the current process environment variable accordingly.
.Link
Set-Env.ArgumentCompleters.ps1
.Parameter Name
Specifies the environment variable name.
.Parameter Value
Specifies the environment variable value.
If it is omitted or empty then the variable is removed.
.Parameter Machine
Tells to update the local Machine variable.
By default it updates the current User variable.
.Link
https://github.com/nightroman/PowerShelf
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=1)]
[string]$Name,
[string]$Value,
[switch]$Machine
)
$ErrorActionPreference = 'Stop'
$target = if ($Machine) {'Machine'} else {'User'}
$ValueOrNull = if ($Value) {$Value} else {[NullString]::Value}
# set registry variable
[System.Environment]::SetEnvironmentVariable($Name, $ValueOrNull, $target)
# special cases
if ($target -eq 'Machine') {
$value2 = [System.Environment]::GetEnvironmentVariable($Name, 'User')
if ($null -ne $value2) {
Write-Warning "Set-Env: Existing User variable '$Name' takes over."
$ValueOrNull = $value2
}
}
elseif ($target -eq 'User' -and !$Value) {
$value2 = [System.Environment]::GetEnvironmentVariable($Name, 'Machine')
if ($null -ne $value2) {
Write-Warning "Set-Env: Existing Machine variable '$Name' takes over."
$ValueOrNull = $value2
}
}
# set process variable
[System.Environment]::SetEnvironmentVariable($Name, $ValueOrNull, 'Process')