返回 CodeWhale
update-user-path.ps1
根目录 / scripts / installer / update-user-path.ps1
1 [CmdletBinding()]
2 param(
3 [ValidateSet('Add', 'Remove')]
4 [string] $Operation,
5
6 [string] $Entry
7 )
8
9 Set-StrictMode -Version Latest
10 $ErrorActionPreference = 'Stop'
11
12 function Get-NormalizedPathEntry {
13 param(
14 [AllowNull()]
15 [AllowEmptyString()]
16 [string] $Value
17 )
18
19 if ($null -eq $Value) {
20 return ''
21 }
22
23 $normalized = $Value.Trim()
24 if (
25 $normalized.Length -ge 2 -and
26 $normalized[0] -eq '"' -and
27 $normalized[$normalized.Length - 1] -eq '"'
28 ) {
29 $normalized = $normalized.Substring(1, $normalized.Length - 2).Trim()
30 }
31
32 return $normalized.TrimEnd([char[]] @('\', '/'))
33 }
34
35 function Test-PathEntryEqual {
36 param(
37 [AllowNull()]
38 [AllowEmptyString()]
39 [string] $Left,
40
41 [AllowNull()]
42 [AllowEmptyString()]
43 [string] $Right
44 )
45
46 $normalizedLeft = Get-NormalizedPathEntry -Value $Left
47 $normalizedRight = Get-NormalizedPathEntry -Value $Right
48
49 if ($normalizedLeft.Length -eq 0 -or $normalizedRight.Length -eq 0) {
50 return $false
51 }
52
53 return [string]::Equals(
54 $normalizedLeft,
55 $normalizedRight,
56 [System.StringComparison]::OrdinalIgnoreCase
57 )
58 }
59
60 function Get-UpdatedUserPath {
61 param(
62 [AllowNull()]
63 [AllowEmptyString()]
64 [string] $Current,
65
66 [Parameter(Mandatory = $true)]
67 [ValidateSet('Add', 'Remove')]
68 [string] $RequestedOperation,
69
70 [Parameter(Mandatory = $true)]
71 [string] $RequestedEntry
72 )
73
74 if ([string]::IsNullOrWhiteSpace((Get-NormalizedPathEntry -Value $RequestedEntry))) {
75 throw 'The PATH entry must not be empty.'
76 }
77
78 if ($null -eq $Current) {
79 $Current = ''
80 }
81
82 $parts = $Current.Split([char[]] @(';'), [System.StringSplitOptions]::None)
83 $containsEntry = $false
84 foreach ($part in $parts) {
85 if (Test-PathEntryEqual -Left $part -Right $RequestedEntry) {
86 $containsEntry = $true
87 break
88 }
89 }
90
91 if ($RequestedOperation -eq 'Add') {
92 if ($containsEntry) {
93 return $Current
94 }
95 if ($Current.Length -eq 0) {
96 return $RequestedEntry
97 }
98 if ($Current.EndsWith(';')) {
99 return "$Current$RequestedEntry;"
100 }
101 return "$Current;$RequestedEntry"
102 }
103
104 if (-not $containsEntry) {
105 return $Current
106 }
107
108 $remaining = New-Object 'System.Collections.Generic.List[string]'
109 foreach ($part in $parts) {
110 if (-not (Test-PathEntryEqual -Left $part -Right $RequestedEntry)) {
111 [void] $remaining.Add($part)
112 }
113 }
114
115 return [string]::Join(';', $remaining)
116 }
117
118 function Set-RegistryPathEntry {
119 param(
120 [Parameter(Mandatory = $true)]
121 [Microsoft.Win32.RegistryKey] $RegistryKey,
122
123 [Parameter(Mandatory = $true)]
124 [ValidateSet('Add', 'Remove')]
125 [string] $RequestedOperation,
126
127 [Parameter(Mandatory = $true)]
128 [string] $RequestedEntry
129 )
130
131 $pathExists = @($RegistryKey.GetValueNames()) -contains 'Path'
132 if ($pathExists) {
133 $valueKind = $RegistryKey.GetValueKind('Path')
134 if (
135 $valueKind -ne [Microsoft.Win32.RegistryValueKind]::String -and
136 $valueKind -ne [Microsoft.Win32.RegistryValueKind]::ExpandString
137 ) {
138 throw "The user PATH has unsupported registry type '$valueKind'."
139 }
140
141 $current = [string] $RegistryKey.GetValue(
142 'Path',
143 $null,
144 [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
145 )
146 if ($null -eq $current) {
147 $current = ''
148 }
149 }
150 else {
151 $current = ''
152 $valueKind = [Microsoft.Win32.RegistryValueKind]::ExpandString
153 }
154
155 $updated = Get-UpdatedUserPath `
156 -Current $current `
157 -RequestedOperation $RequestedOperation `
158 -RequestedEntry $RequestedEntry
159
160 if ([string]::Equals($current, $updated, [System.StringComparison]::Ordinal)) {
161 return $false
162 }
163
164 $RegistryKey.SetValue('Path', $updated, $valueKind)
165 return $true
166 }
167
168 function Set-CodeWhaleUserPath {
169 param(
170 [Parameter(Mandatory = $true)]
171 [ValidateSet('Add', 'Remove')]
172 [string] $RequestedOperation,
173
174 [Parameter(Mandatory = $true)]
175 [string] $RequestedEntry
176 )
177
178 if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) {
179 throw 'The CodeWhale user PATH helper only supports Windows.'
180 }
181
182 $environmentKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
183 if ($null -eq $environmentKey) {
184 throw 'Could not open or create the current-user Environment registry key.'
185 }
186
187 try {
188 return Set-RegistryPathEntry `
189 -RegistryKey $environmentKey `
190 -RequestedOperation $RequestedOperation `
191 -RequestedEntry $RequestedEntry
192 }
193 finally {
194 $environmentKey.Close()
195 }
196 }
197
198 if ($MyInvocation.InvocationName -ne '.') {
199 if ([string]::IsNullOrWhiteSpace($Operation)) {
200 throw 'Operation is required.'
201 }
202 if ([string]::IsNullOrWhiteSpace($Entry)) {
203 throw 'Entry is required.'
204 }
205
206 $changed = Set-CodeWhaleUserPath `
207 -RequestedOperation $Operation `
208 -RequestedEntry $Entry
209
210 if ($changed) {
211 Write-Host "User PATH updated: $Operation '$Entry'."
212 }
213 else {
214 Write-Host "User PATH already satisfied: $Operation '$Entry'."
215 }
216 }
217
217 lines Plain Text