-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathRemove-EnvironmentVariableValue.ps1
87 lines (67 loc) · 4.38 KB
/
Remove-EnvironmentVariableValue.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<#
$Metadata = @{
Title = "Remove Environment Variable Value"
Filename = "Remove-EnvironmentVariableValue.ps1"
Description = ""
Tags = "powershell, function, remove, environment, vairable"
Project = ""
Author = "Janik von Rotz"
AuthorContact = "http://janikvonrotz.ch"
CreateDate = "2014-02-21"
LastEditDate = "2014-02-23"
Url = ""
Version = "0.0.1"
License = @'
This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Switzerland License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ch/ or
send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
'@
}
#>
function Remove-EnvironmentVariableValue{
<#
.SYNOPSIS
Removes value of an environment variable.
.DESCRIPTION
Removes value of an environment variable.
.PARAMETER Name
Name of the variable.
.PARAMETER Value
Value to remove.
.PARAMETER Target
Scope of the variable. Machine or User.
.PARAMETER Clear
Clear this variable.
.EXAMPLE
PS C:\> Remove-EnvironmentVariableValue -Name Path -Value ";C:\bin" -Target Machine
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]
$Name,
[Parameter(Mandatory=$true)]
[String]
$Value,
[Parameter(Mandatory=$true)]
[String]
$Target,
[Switch]
$Clear
)
#--------------------------------------------------#
# main
#--------------------------------------------------#
[Environment]::GetEnvironmentVariable($Name,$Target) | %{
if(($_.Contains($Value) -or (Invoke-Expression "`$env:$Name").contains($Value)) -and -not $Clear){
Write-Host "Remove value: $Value from variable: $Name"
$Value = $_.Trim($Value)
[Environment]::SetEnvironmentVariable($Name, $Value,$Target)
Invoke-Expression "`$env:$Name = `"$Value`""
}elseif($Clear){
Write-Host "Set value from variable: $Name to `$null"
[Environment]::SetEnvironmentVariable($Name,$null,$Target)
Invoke-Expression "`$env:$Name = `$null"
}
}
}