-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuninstall.ps1
More file actions
479 lines (439 loc) · 23.9 KB
/
Copy pathuninstall.ps1
File metadata and controls
479 lines (439 loc) · 23.9 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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# Java Version Manager
# Copyright (C) 2026 DiamTek / Alexéy Shishkin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
[CmdletBinding()]
param(
[switch]$Quiet,
[switch]$DeleteJava,
[switch]$DeleteTarget,
[string]$SourceDir
)
$ErrorActionPreference = 'Continue'
$ProgressPreference = 'SilentlyContinue'
Write-Host ""
Write-Host "============================================================"
Write-Host " Java Version Manager - Uninstaller"
Write-Host "============================================================"
Write-Host ""
# ----------------------------------------------------------------
# PATH cleanup - remove ALL known JVM install locations from User PATH.
# Machine PATH is read-only without elevation; we attempt it silently
# and skip if it fails (JVM never writes to Machine PATH in normal use).
# ----------------------------------------------------------------
Write-Host "[ ACTION ] Removing JVM from system PATH..." -ForegroundColor Cyan
$systemPowerShell = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
if (-not (Test-Path $systemPowerShell)) { $systemPowerShell = "powershell.exe" }
$localAppData = [Environment]::GetFolderPath('LocalApplicationData')
$jvmLocations = @(
"$localAppData\DiamTek\JVM\bin",
"$localAppData\DiamTek\JVM\current\bin"
)
# Also remove SourceDir and its bin folder if provided
if ($SourceDir) {
if ($jvmLocations -notcontains $SourceDir) { $jvmLocations += $SourceDir }
$sourceBin = Join-Path $SourceDir "bin"
if ($jvmLocations -notcontains $sourceBin) { $jvmLocations += $sourceBin }
}
# Also remove the script's own directory if it differs
$scriptDir = Split-Path -Parent $PSCommandPath
if ($scriptDir -and ($jvmLocations -notcontains $scriptDir)) {
$jvmLocations += $scriptDir
}
$normJvmLocations = @($jvmLocations | ForEach-Object { $_.TrimEnd('\', '/') } | Where-Object { $_ } | Select-Object -Unique)
function Test-IsJvmPath([string]$p) {
if (-not $p) { return $false }
$cleanP = $p.Trim().TrimEnd('\', '/')
foreach ($loc in $normJvmLocations) {
if ([string]::Equals($cleanP, $loc, [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
return $false
}
try {
$userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
if ($userKey) {
$rawUserPath = $userKey.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
if ($null -ne $rawUserPath -and $rawUserPath -ne '') {
$userKind = try { $userKey.GetValueKind('Path') } catch { [Microsoft.Win32.RegistryValueKind]::String }
$cleanUser = ($rawUserPath -split ';' | Where-Object { $_ -and -not (Test-IsJvmPath $_) }) -join ';'
$targetKind = if ($userKind -eq [Microsoft.Win32.RegistryValueKind]::String) { [Microsoft.Win32.RegistryValueKind]::String } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }
$userKey.SetValue('Path', $cleanUser, $targetKind)
Write-Host "[ OK ] User PATH cleaned." -ForegroundColor Green
}
$userKey.Close()
}
} catch {
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
if ($userPath) {
$cleanUser = ($userPath -split ';' | Where-Object { $_ -and -not (Test-IsJvmPath $_) }) -join ';'
[Environment]::SetEnvironmentVariable('Path', $cleanUser, 'User')
Write-Host "[ OK ] User PATH cleaned." -ForegroundColor Green
}
}
# Attempt Machine PATH cleanup (silently skipped if no elevation)
try {
$machineKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)
if ($machineKey) {
$rawMachinePath = $machineKey.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
if ($null -ne $rawMachinePath -and $rawMachinePath -ne '') {
$machineKind = try { $machineKey.GetValueKind('Path') } catch { [Microsoft.Win32.RegistryValueKind]::String }
$cleanMachine = ($rawMachinePath -split ';' | Where-Object { $_ -and -not (Test-IsJvmPath $_) }) -join ';'
$targetKind = if ($machineKind -eq [Microsoft.Win32.RegistryValueKind]::String) { [Microsoft.Win32.RegistryValueKind]::String } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }
$machineKey.SetValue('Path', $cleanMachine, $targetKind)
}
$machineKey.Close()
}
} catch { <# No elevation - skip silently #> }
# Broadcast WM_SETTINGCHANGE so running terminals pick up the new PATH
try {
if (-not ('Win32.NativeMethods' -as [type])) {
Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @'
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
'@
}
$HWND_BROADCAST = [IntPtr]0xFFFF
$WM_SETTINGCHANGE = 0x001A
$result = [UIntPtr]::Zero
[Win32.NativeMethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result) | Out-Null
} catch { <# Non-critical - ignore #> }
# ----------------------------------------------------------------
# PowerShell profile hook removal - all PS versions
# ----------------------------------------------------------------
Write-Host "[ ACTION ] Removing PowerShell Profile Hook..." -ForegroundColor Cyan
$userProfileDir = [Environment]::GetFolderPath('UserProfile')
$myDocs = [Environment]::GetFolderPath('MyDocuments')
$profiles = @(
(Join-Path $userProfileDir "Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"),
(Join-Path $userProfileDir "Documents\PowerShell\Microsoft.PowerShell_profile.ps1"),
(Join-Path $myDocs "WindowsPowerShell\Microsoft.PowerShell_profile.ps1"),
(Join-Path $myDocs "PowerShell\Microsoft.PowerShell_profile.ps1"),
$PROFILE
) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
$blockPattern = '(?s)# >>> jvm >>>.*?# <<< jvm <<<'
foreach ($p in $profiles) {
if (Test-Path $p) {
$profContent = Get-Content $p -Raw -ErrorAction SilentlyContinue
$m = [Regex]::Match($profContent, $blockPattern)
if ($m.Success) {
$profContent = $profContent.Remove($m.Index, $m.Length).Trim()
if ([string]::IsNullOrWhiteSpace($profContent)) {
Remove-Item $p -Force -ErrorAction SilentlyContinue
} else {
Set-Content -Path $p -Value $profContent -Encoding UTF8
}
Write-Host "[ OK ] Profile hook removed from: $p" -ForegroundColor Green
}
}
}
# ----------------------------------------------------------------
# Environment variables
# ----------------------------------------------------------------
Write-Host "`n[ ACTION ] Cleaning up Environment Variables..." -ForegroundColor Cyan
$vars = @('JAVA_HOME', 'MAVEN_HOME', 'GRADLE_HOME', 'KOTLIN_HOME', 'SCALA_HOME', 'GROOVY_HOME')
$removedVars = 0
foreach ($v in $vars) {
foreach ($scope in @('User', 'Machine')) {
try {
$val = [Environment]::GetEnvironmentVariable($v, $scope)
if ($val) {
[Environment]::SetEnvironmentVariable($v, $null, $scope)
$removedVars++
}
} catch { <# Machine scope may need elevation - skip silently #> }
}
}
Write-Host "[ OK ] Removed $removedVars environment variables." -ForegroundColor Green
# ----------------------------------------------------------------
# Registry uninstall entry + Start Menu shortcuts
# ----------------------------------------------------------------
Write-Host "`n[ ACTION ] Removing Windows Uninstall Registry & Shortcuts..." -ForegroundColor Cyan
Remove-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\DiamTek.JVM" -Recurse -Force -ErrorAction SilentlyContinue
try { Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\DiamTek.JVM" -Recurse -Force -ErrorAction SilentlyContinue } catch {}
Remove-Item -Path "HKCU:\Software\DiamTek\JVM" -Recurse -Force -ErrorAction SilentlyContinue
try { Remove-Item -Path "HKLM:\Software\DiamTek\JVM" -Recurse -Force -ErrorAction SilentlyContinue } catch {}
# Only prune parent DiamTek registry key if it has no remaining subkeys or values
try {
$cuDiamTek = Get-Item -Path "HKCU:\Software\DiamTek" -ErrorAction SilentlyContinue
if ($cuDiamTek -and ($cuDiamTek.SubKeyCount -eq 0) -and ($cuDiamTek.ValueCount -eq 0)) {
Remove-Item -Path "HKCU:\Software\DiamTek" -Force -ErrorAction SilentlyContinue
}
} catch {}
try {
$lmDiamTek = Get-Item -Path "HKLM:\Software\DiamTek" -ErrorAction SilentlyContinue
if ($lmDiamTek -and ($lmDiamTek.SubKeyCount -eq 0) -and ($lmDiamTek.ValueCount -eq 0)) {
Remove-Item -Path "HKLM:\Software\DiamTek" -Force -ErrorAction SilentlyContinue
}
} catch {}
$startMenuDirs = @(
(Join-Path ([Environment]::GetFolderPath('Programs')) "DiamTek"),
(Join-Path ([Environment]::GetFolderPath('CommonPrograms')) "DiamTek")
)
foreach ($sm in $startMenuDirs) {
if (Test-Path $sm) {
Get-ChildItem -LiteralPath $sm -Filter "*Java Version Manager*" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
Get-ChildItem -LiteralPath $sm -Filter "*JVM*" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
$remaining = Get-ChildItem -LiteralPath $sm -Force -ErrorAction SilentlyContinue
if (-not $remaining) {
Remove-Item -LiteralPath $sm -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "[ OK ] Removed Start Menu folder: $sm" -ForegroundColor Green
}
}
}
$taskbarLnk = Join-Path $env:APPDATA "Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Java Version Manager.lnk"
if (Test-Path $taskbarLnk) {
Remove-Item -Path $taskbarLnk -Force -ErrorAction SilentlyContinue
Write-Host "[ OK ] Removed pinned Taskbar shortcut." -ForegroundColor Green
}
# Windows Terminal Profile cleanup
$wtSettingsCandidates = @(
"$env:LOCALAPPDATA\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json",
"$env:LOCALAPPDATA\Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json",
"$env:LOCALAPPDATA\Microsoft\Windows Terminal\settings.json"
)
foreach ($wtSettings in $wtSettingsCandidates) {
if (Test-Path $wtSettings) {
try {
$wtContent = Get-Content $wtSettings -Raw -ErrorAction Stop
$cleanJson = $wtContent -replace '(?m)^\s*//.*$', ''
$wtJson = $cleanJson | ConvertFrom-Json
if ($wtJson.profiles -and $wtJson.profiles.list) {
$filtered = @($wtJson.profiles.list | Where-Object { $_.guid -ne '{b20650a4-4212-4d64-9edf-744e9285e2be}' -and $_.name -ne 'Java Version Manager' })
if ($filtered.Count -ne $wtJson.profiles.list.Count) {
$wtJson.profiles.list = $filtered
if ($wtJson.defaultProfile -eq '{b20650a4-4212-4d64-9edf-744e9285e2be}' -and $filtered.Count -gt 0) {
$wtJson.defaultProfile = $filtered[0].guid
}
$newWtContent = $wtJson | ConvertTo-Json -Depth 32
Set-Content $wtSettings $newWtContent -Encoding utf8
Write-Host "[ OK ] Removed Windows Terminal profile." -ForegroundColor Green
}
}
} catch { }
}
}
# Cleanup temporary session files
Remove-Item -Path "$env:TEMP\.jvm_session_target" -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:TEMP -Filter "jvm_*" -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -notmatch 'uninstall' } | Remove-Item -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:TEMP -Filter "diamtek_uninstall_*" -File -ErrorAction SilentlyContinue | Where-Object { $_.FullName -ne $PSCommandPath } | Remove-Item -Force -ErrorAction SilentlyContinue
Write-Host "[ OK ] Windows uninstall registration removed." -ForegroundColor Green
# ----------------------------------------------------------------
# AppData & Ecosystem Candidate folders - always removed on a complete uninstall
# ----------------------------------------------------------------
Write-Host "`n[ ACTION ] Deleting JVM AppData and Candidate folders..." -ForegroundColor Cyan
$diamtekAppData = Join-Path $localAppData "DiamTek"
$jvmAppData = Join-Path $diamtekAppData "JVM"
if (Test-Path $jvmAppData) {
# Terminate any dangling JVM processes locking files
try {
Get-Process | Where-Object {
try {
$_.Path -and $_.Path.StartsWith($jvmAppData, [System.StringComparison]::OrdinalIgnoreCase)
} catch { $false }
} | Stop-Process -Force -ErrorAction SilentlyContinue
} catch { }
# Safely unbind and remove any directory junctions / reparse points first
# This prevents Windows PowerShell 5.1 Remove-Item -Recurse from traversing
# into target JDK installation folders (e.g. C:\Program Files\Java\jdk-*)
try {
Get-ChildItem -LiteralPath $jvmAppData -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {
$_.Attributes -band [System.IO.FileAttributes]::ReparsePoint
} | ForEach-Object {
if ($_.PSIsContainer) {
try {
[System.IO.Directory]::Delete($_.FullName, $false)
} catch {
cmd.exe /c "rmdir /q `"$($_.FullName)`"" 2>$null
}
} else {
Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
}
}
} catch { }
try {
Remove-Item -LiteralPath $jvmAppData -Recurse -Force -ErrorAction Stop
Write-Host "[ OK ] Deleted: $jvmAppData" -ForegroundColor Green
} catch {
$cleanScript = "Start-Sleep -Seconds 1; if (Test-Path -LiteralPath '$($jvmAppData -replace "'", "''")') { Remove-Item -LiteralPath '$($jvmAppData -replace "'", "''")' -Recurse -Force -ErrorAction SilentlyContinue }"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($cleanScript)
$encoded = [System.Convert]::ToBase64String($bytes)
Start-Process -FilePath $systemPowerShell -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", $encoded) -WindowStyle Hidden
Write-Host "[ OK ] Scheduled deletion of: $jvmAppData" -ForegroundColor Green
}
} else {
Write-Host "[ OK ] AppData folder already missing." -ForegroundColor Green
}
if (Test-Path $diamtekAppData) {
$remaining = Get-ChildItem -LiteralPath $diamtekAppData -Force -ErrorAction SilentlyContinue
if (-not $remaining) {
Remove-Item -LiteralPath $diamtekAppData -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "[ OK ] Cleaned up parent directory: $diamtekAppData" -ForegroundColor Green
}
}
# Legacy and shared state folders
$legacyJvm = Join-Path $localAppData "JavaVersionManager"
if (Test-Path $legacyJvm) {
Remove-Item -LiteralPath $legacyJvm -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "[ OK ] Cleaned up: $legacyJvm" -ForegroundColor Green
}
# Candidate tools and caches (Maven, Gradle, etc. in ~/.jvm)
$userJvmCandidates = Join-Path $userProfileDir ".jvm"
if (Test-Path $userJvmCandidates) {
try {
Get-ChildItem -LiteralPath $userJvmCandidates -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {
$_.Attributes -band [System.IO.FileAttributes]::ReparsePoint
} | ForEach-Object {
if ($_.PSIsContainer) {
try {
[System.IO.Directory]::Delete($_.FullName, $false)
} catch {
cmd.exe /c "rmdir /q `"$($_.FullName)`"" 2>$null
}
} else {
Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
}
}
} catch { }
Remove-Item -LiteralPath $userJvmCandidates -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "[ OK ] Cleaned up candidates folder: $userJvmCandidates" -ForegroundColor Green
}
# ----------------------------------------------------------------
# JDK folder - only prompt if C:\Program Files\Java actually exists
# ----------------------------------------------------------------
$javaDir = if (Test-Path "C:\Program Files\Java") { "C:\Program Files\Java" } elseif ($env:ProgramFiles -and (Test-Path (Join-Path $env:ProgramFiles "Java"))) { Join-Path $env:ProgramFiles "Java" } else { $null }
if ($javaDir) {
Write-Host ""
Write-Host "============================================================"
Write-Host "[ WARNING] JVM installs JDKs into '$javaDir'." -ForegroundColor Yellow
$shouldDeleteJava = $DeleteJava -or $false
if (-not $shouldDeleteJava -and -not $Quiet) {
$confirmJava = Read-Host "Do you want to PERMANENTLY DELETE '$javaDir' and ALL installed JDKs? (y/N)"
if ($confirmJava -match '^y') {
$shouldDeleteJava = $true
}
}
if ($shouldDeleteJava) {
Write-Host "[ ACTION ] Deleting $javaDir..." -ForegroundColor Cyan
$deleted = $false
try {
Remove-Item -LiteralPath $javaDir -Recurse -Force -ErrorAction Stop
$deleted = $true
} catch {
Write-Host "[ ACTION ] Requesting Administrator privileges to delete '$javaDir'..." -ForegroundColor Cyan
try {
$delScript = "Remove-Item -LiteralPath '$($javaDir -replace "'", "''")' -Recurse -Force -ErrorAction SilentlyContinue"
$encDel = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($delScript))
$proc = Start-Process -FilePath $systemPowerShell -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", $encDel) -Verb RunAs -Wait -PassThru
if (-not (Test-Path $javaDir)) {
$deleted = $true
}
} catch {
Write-Host "[ ERROR ] Administrator elevation was declined or failed." -ForegroundColor Red
}
}
if ($deleted -and (-not (Test-Path $javaDir))) {
Write-Host "[ OK ] JDK installation directory deleted." -ForegroundColor Green
} else {
Write-Host "[ ERROR ] Could not delete '$javaDir'. Please remove it manually." -ForegroundColor Red
}
}
}
# ----------------------------------------------------------------
# Standalone / workspace cleanup (if running from a portable copy outside AppData)
# ----------------------------------------------------------------
$targetFolder = $null
if ($SourceDir -and (Test-Path $SourceDir)) {
$targetFolder = (Resolve-Path $SourceDir).Path
} elseif ($scriptDir -and (Test-Path $scriptDir)) {
$targetFolder = (Resolve-Path $scriptDir).Path
}
if ($targetFolder) {
$normalizedAppData = Join-Path $localAppData "DiamTek"
if (Test-Path $normalizedAppData) { $normalizedAppData = (Resolve-Path $normalizedAppData).Path }
# If target is outside AppData and outside Temp, check standalone / test copy
if (-not $targetFolder.StartsWith($normalizedAppData, [StringComparison]::OrdinalIgnoreCase) -and -not $targetFolder.StartsWith($env:TEMP, [StringComparison]::OrdinalIgnoreCase)) {
# Protect active development repository from accidental deletion
$isDevRepo = (Test-Path (Join-Path $targetFolder ".git")) -or (Test-Path (Join-Path $targetFolder "..\.git"))
if ($isDevRepo) {
Write-Host "`n[ INFO ] Active development repository detected at: $targetFolder" -ForegroundColor Yellow
Write-Host " Source repository will NOT be deleted." -ForegroundColor Yellow
} else {
$deleteTarget = $DeleteTarget -or $false
if (-not $deleteTarget -and -not $Quiet) {
$confirmTarget = Read-Host "`nDo you also want to delete this JVM directory and all its files? ($targetFolder) (y/N)"
if ($confirmTarget -match '^y') {
$deleteTarget = $true
}
}
if ($deleteTarget) {
Write-Host "[ ACTION ] Deleting JVM directory: $targetFolder..." -ForegroundColor Cyan
Set-Location $env:TEMP
# Unbind junctions before removing target folder
try {
Get-ChildItem -LiteralPath $targetFolder -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {
$_.Attributes -band [System.IO.FileAttributes]::ReparsePoint
} | ForEach-Object {
if ($_.PSIsContainer) {
try { [System.IO.Directory]::Delete($_.FullName, $false) } catch { cmd.exe /c "rmdir /q `"$($_.FullName)`"" 2>$null }
} else {
Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
}
}
} catch { }
try {
Remove-Item -LiteralPath $targetFolder -Recurse -Force -ErrorAction Stop
Write-Host "[ OK ] Deleted directory: $targetFolder" -ForegroundColor Green
} catch {
$cleanScript = "Start-Sleep -Seconds 2; if (Test-Path -LiteralPath '$($targetFolder -replace "'", "''")') { Remove-Item -LiteralPath '$($targetFolder -replace "'", "''")' -Recurse -Force -ErrorAction SilentlyContinue }"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($cleanScript)
$encoded = [System.Convert]::ToBase64String($bytes)
Start-Process -FilePath $systemPowerShell -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", $encoded) -WindowStyle Hidden
Write-Host "[ OK ] Directory scheduled for deletion: $targetFolder" -ForegroundColor Green
}
# Clean up parent container folder if it is an empty test directory inside TEMP
$parentDir = Split-Path -Parent $targetFolder
$tempDir = [System.IO.Path]::GetFullPath($env:TEMP)
if ($parentDir -and (Test-Path $parentDir)) {
$parentFull = [System.IO.Path]::GetFullPath($parentDir)
$parentName = Split-Path -Leaf $parentFull
if ($parentFull.StartsWith($tempDir, [System.StringComparison]::OrdinalIgnoreCase) -and ($parentName -match '^(jvm-test|diamtek-temp)')) {
$remaining = Get-ChildItem -LiteralPath $parentFull -Force -ErrorAction SilentlyContinue
if (-not $remaining) {
Remove-Item -LiteralPath $parentFull -Force -Recurse -ErrorAction SilentlyContinue
}
}
}
}
}
}
}
Write-Host ""
Write-Host "============================================================"
Write-Host "[ OK ] Uninstallation Complete." -ForegroundColor Green
Write-Host " Please close and restart all terminals for environment changes to take effect."
Write-Host ""
if (-not $Quiet) {
Write-Host "Press any key to exit..."
try {
if ([System.Console]::IsInputRedirected) {
$null = [System.Console]::ReadLine()
} else {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
} catch {
# Fallback if console is non-interactive
}
}