如果不加以管理,Java運行環境在企業中可能會像野火般擴散。當我運行報告查看我的環境中的Java情況時,我發現了62個不同版本的Java!是時候重新掌控並建立一個PowerShell腳本來刪除舊版本的Java了。
在這個教程中,您將學習如何使用PowerShell創建一個用於刪除舊版Java的Java刪除工具。
讓我們開始吧!
創建腳本
首先,打開您喜歡的代碼編輯器,如Visual Studio Code,並將文件保存為Remove-Java.ps1。這個PowerShell腳本將包含您清理之前Java版本所需的一切。
定義注冊表路徑
由於Java實例可能會隱藏在註冊表的兩個地方,首先定義每個父注冊表鍵。下面的代碼片段提供了32位和64位注冊表路徑。
定義要保留的版本
因為您可能想要保留一些舊版本的Java,所以創建一個包含您想要保留的每個版本的數組。
您可以通過查看控制面板中的“程序和功能”找到要使用的確切文本。
查找並停止所有運行中的進程
接下來,找到所有正在運行的Java進程。下面的代碼片段使用WMI列舉了所有運行的進程,這些進程與路徑匹配“Program Files\Java”。
由於Java可能嵌入到Internet Explorer中並且無法刪除,請繼續停止所有Internet Explorer進程。
尋找在註冊表中的Java並強制卸載
接下來,建立一個篩選器,用於列舉在上面定義的註冊表鍵下的所有值。此篩選器尋找所有的Java實例並排除您想要保留的所有版本。
現在在註冊表中搜索所有Java實例,如果找到,運行msiexec.exe /X
以刪除每個實例。
刪除任何舊的Java殘留
清理Java卸載程序自行無法清除的任何殘留物。
完成
就是這樣!在每台要清理Java的計算機上運行此PowerShell腳本,以使此過程盡可能無縫。
隨時在下方一次性下載整個腳本。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$RegUninstallPaths = @( | |
‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall‘, | |
‘HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall‘ | |
) | |
$VersionsToKeep = @(‘Java 8 Update 261‘) | |
Get-CimInstance –ClassName ‘Win32_Process‘ | Where-Object {$_.ExecutablePath -like ‘*Program Files\Java*‘} | | |
Select-Object @{n=‘Name‘;e={$_.Name.Split(‘.‘)[0]}} | Stop-Process –Force | |
Get-process –Name *iexplore* | Stop-Process –Force –ErrorAction SilentlyContinue | |
$UninstallSearchFilter = {($_.GetValue(‘DisplayName‘) -like ‘*Java*‘) -and (($_.GetValue(‘Publisher‘) -eq ‘Oracle Corporation‘)) -and ($VersionsToKeep -notcontains $_.GetValue(‘DisplayName‘))} | |
# Uninstall unwanted Java versions and clean up program files | |
foreach ($Path in $RegUninstallPaths) { | |
if (Test-Path $Path) { | |
Get-ChildItem $Path | Where-Object $UninstallSearchFilter | | |
foreach { | |
Start-Process ‘C:\Windows\System32\msiexec.exe‘ “/X$($_.PSChildName) /qn“ –Wait | |
} | |
} | |
} | |
New-PSDrive –Name HKCR –PSProvider Registry –Root HKEY_CLASSES_ROOT | Out-Null | |
$ClassesRootPath = “HKCR:\Installer\Products“ | |
Get-ChildItem $ClassesRootPath | | |
Where-Object { ($_.GetValue(‘ProductName‘) -like ‘*Java*‘)} | Foreach { | |
Remove-Item $_.PsPath –Force –Recurse | |
} | |
$JavaSoftPath = ‘HKLM:\SOFTWARE\JavaSoft‘ | |
if (Test-Path $JavaSoftPath) { | |
Remove-Item $JavaSoftPath –Force –Recurse | |
} |
感謝Sam Turner幫助我修復此代碼的一些錯誤。