Active Directory Health Check: PowerShell Scripting

Published:30 June 2019 - 2 min. read

If left unattended, Java runtime environments can spread like wildfire in an enterprise. When I ran a report to find out what the Java landscape looked like in my environment, I found 62 different versions of Java! It’s time to take back control and build a PowerShell script for removing old Java versions.

In this tutorial, you’re going to learn how to create a Java removal tool for removing old Java in PowerShell.

Let’s get started!

Creating the Script

First, open up your favorite code editor like Visual Studio Code and save the file as Remove-Java.ps1. This PowerShell script will contain everything you need to clean up previous Java versions.

Define the Registry Paths

Because Java instances can hide in two places in the registry, first define each of the parent registry keys. The below code snippet provides both the 32 and 64-bit registry paths.

$RegUninstallPaths = @(
   'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
    'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
)

Define Versions to Keep

Because you probably want to keep some old versions of Java out there, create an array with each of the versions you’d like to keep.

You can find the exact text to use by looking at Programs and Features in the Control Panel.

$VersionsToKeep = @('Java 8 Update 261')

Find and Stop all Running Processes

Next, find all of the running Java processes. The code snippet below enumerates all of the running processes with WMI that are running with a file in a path matching “Program Files\Java“.

Since Java can embed itself within Internet Explorer and can’t be removed, go ahead and also stop all Internet Explorer processes too.

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

Search for Java in the Registry and Force an Uninstall

Next, build a filter that you’ll use to enumerate all of the values under the registry keys defined above. This filter finds all of the Java instances and excludes all versions you’d like to keep.

$UninstallSearchFilter = {($_.GetValue('DisplayName') -like '*Java*') -and (($_.GetValue('Publisher') -eq 'Oracle Corporation')) -and ($VersionsToKeep -notcontains $_.GetValue('DisplayName'))}

Now search through the registry to find all Java instances and, if found, run msiexec.exe /X to remove each instance.

# 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
    
        }
    }
}

Remove any Old Java Remnants

Clean up any remnants that the Java uninstaller doesn’t get rid of on its own.

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
}

Wrap up

And that’s it! Run this PowerShell script on each computer you’d like to cleanup Java on to make this process as seamless as possible.

Feel free to download the entire script at once below.

Thanks to Sam Turner for helping me fix some bugs with this code.

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!