Notification

Icon
Error

Script - Remove Old Java Versions Silently - Silently remove old versions of 32-bit and 64-bit JRE.

Posted: Friday, April 24, 2015 8:05:42 AM(UTC)
Kinetic

Kinetic

Member Original PosterPosts: 4
17
Like
This package checks for both 32-bit and 64-bit installed versions of Java, and silently uninstalls any old versions leaving behind only the newest.

Keeping old versions of Java on your system presents a serious security risk.
Uninstalling older versions of Java from your system ensures that Java applications will run with the latest security and performance improvements on your system.

Either download the attached script, or copy the code below and save it as Remove_old_java_versions.ps1 at the {PackageShare}\Scripts folder

Notes:
- As this is just a simple Powershell script, it can also be run on its own.
- The script is a little slow as enumerating the WMI class Win32_Product takes a long time.

Update: Version 1.1 @ 2015-05-20
- Now also detects and uninstalls old Java non-update base versions (i.e. Java versions without Update #)
- Now also removes Java 6 and below, plus added ability to manually change this behaviour.
- Added uninstall default behaviour to never reboot (now uses msiexec.exe for uninstall)
Update: Version 1.2 @ 2015-07-28
- Bug fixes: null array and op_addition errors.

Code:
#This script is used to remove any old Java versions, and leave only the newest.
#Original author: mmcpherson
#Version 1.0 - created 2015-04-24
#Version 1.1 - updated 2015-05-20
#            - Now also detects and removes old Java non-update base versions (i.e. Java versions without Update #)
#            - Now also removes Java 6 and below, plus added ability to manually change this behaviour.
#            - Added uninstall default behaviour to never reboot (now uses msiexec.exe for uninstall)
#Version 1.2 - updated 2015-07-28
#            - Bug fixes: null array and op_addition errors.
#
#
# IMPORTANT NOTE: If you would like Java versions 6 and below to remain, please edit the next line and replace $true with $false
$UninstallJava6andBelow = $true

#Declare version arrays
$32bitJava = @()
$64bitJava = @()
$32bitVersions = @()
$64bitVersions = @()

#Perform WMI query to find installed Java Updates
if ($UninstallJava6andBelow) {
    $32bitJava += Get-WmiObject -Class Win32_Product | Where-Object { 
        $_.Name -match "(?i)Java(\(TM\))*\s\d+(\sUpdate\s\d+)*$"
    }
    #Also find Java version 5, but handled slightly different as CPU bit is only distinguishable by the GUID
    $32bitJava += Get-WmiObject -Class Win32_Product | Where-Object { 
        ($_.Name -match "(?i)J2SE\sRuntime\sEnvironment\s\d[.]\d(\sUpdate\s\d+)*$") -and ($_.IdentifyingNumber -match "^\{32")
    }
} else {
    $32bitJava += Get-WmiObject -Class Win32_Product | Where-Object { 
	    $_.Name -match "(?i)Java((\(TM\) 7)|(\s\d+))(\sUpdate\s\d+)*$" 
    }
}

#Perform WMI query to find installed Java Updates (64-bit)
if ($UninstallJava6andBelow) {
    $64bitJava += Get-WmiObject -Class Win32_Product | Where-Object { 
	    $_.Name -match "(?i)Java(\(TM\))*\s\d+(\sUpdate\s\d+)*\s[(]64-bit[)]$" 
    }
    #Also find Java version 5, but handled slightly different as CPU bit is only distinguishable by the GUID
    $64bitJava += Get-WmiObject -Class Win32_Product | Where-Object { 
        ($_.Name -match "(?i)J2SE\sRuntime\sEnvironment\s\d[.]\d(\sUpdate\s\d+)*$") -and ($_.IdentifyingNumber -match "^\{64")
    }
} else {
    $64bitJava += Get-WmiObject -Class Win32_Product | Where-Object { 
	    $_.Name -match "(?i)Java((\(TM\) 7)|(\s\d+))(\sUpdate\s\d+)*\s[(]64-bit[)]$" 
    }
}

#Enumerate and populate array of versions
Foreach ($app in $32bitJava) {
	if ($app -ne $null) { $32bitVersions += $app.Version }
}

#Enumerate and populate array of versions
Foreach ($app in $64bitJava) {
	if ($app -ne $null) { $64bitVersions += $app.Version }
}

#Create an array that is sorted correctly by the actual Version (as a System.Version object) rather than by value.
$sorted32bitVersions = $32bitVersions | %{ New-Object System.Version ($_) } | sort
$sorted64bitVersions = $64bitVersions | %{ New-Object System.Version ($_) } | sort
#If a single result is returned, convert the result into a single value array so we don't run in to trouble calling .GetUpperBound later
if($sorted32bitVersions -isnot [system.array]) { $sorted32bitVersions = @($sorted32bitVersions)}
if($sorted64bitVersions -isnot [system.array]) { $sorted64bitVersions = @($sorted64bitVersions)}
#Grab the value of the newest version from the array, first converting 
$newest32bitVersion = $sorted32bitVersions[$sorted32bitVersions.GetUpperBound(0)]
$newest64bitVersion = $sorted64bitVersions[$sorted64bitVersions.GetUpperBound(0)]

Foreach ($app in $32bitJava) {
	if ($app -ne $null)
	{
		# Remove all versions of Java, where the version does not match the newest version.
		if (($app.Version -ne $newest32bitVersion) -and ($newest32bitVersion -ne $null)) {
		   $appGUID = $app.Properties["IdentifyingNumber"].Value.ToString()
		   Start-Process -FilePath "msiexec.exe" -ArgumentList "/qn /norestart /x $($appGUID)" -Wait -Passthru
		   #write-host "Uninstalling 32-bit version: " $app
		}
	}
}

Foreach ($app in $64bitJava) {
	if ($app -ne $null)
	{
		# Remove all versions of Java, where the version does not match the newest version.
		if (($app.Version -ne $newest64bitVersion) -and ($newest64bitVersion -ne $null)) {
		$appGUID = $app.Properties["IdentifyingNumber"].Value.ToString()
		   Start-Process -FilePath "msiexec.exe" -ArgumentList "/qn /norestart /x $($appGUID)" -Wait -Passthru
		   #write-host "Uninstalling 64-bit version: " $app
		}
	}
}
Handles attachments
Remove_old_java_versions.zip (2kb) downloaded 1,958 time(s).
Remove_old_java_versions v1.2.zip (2kb) downloaded 7,487 time(s).
Script - Remove Old Java Runtime VersionsDownload Package
DescriptionThis package checks for both 32-bit and 64-bit installed versions of JRE, and silently removes any old versions leaving behind only the newest.

Keeping old versions of Java on your system presents a serious security risk.
Uninstalling older versions of Java from your system ensures that Java applications will run with the latest security and performance improvements on your system.
Final ActionNothing
Max. Duration5 min(s), 0 hour(s)
RescanNo
Steps
1. Check for script
TypeCondition
SuccessGo To Step 2
FailureStop (Failure)
Conditions
File {PackageShare}\Scripts Remove_old_java_versions.ps1 Exists
2. Call script
TypeCommand
Return Codes 0,1641,3010
SuccessStop (Success)
FailureStop (Failure)
Command powershell -executionpolicy bypass -File "{PackageShare}\Scripts\Remove_old_java_versions.ps1"
PeterG
#1PeterG Member Posts: 104  
posted: 5/7/2015 6:22:01 PM(UTC)
love this script.. thank you..

Quick Side Note:

Oracle changed the naming conversion for its Java products after version 6 example

Java(TM) 6 Update 10 to Java 8 Update 10 so this script only will uninstall version 7+ which is OK for us because version 6 is required for 1 legacy app.
hisax
#2hisax Member Posts: 2  
posted: 5/19/2015 8:31:31 AM(UTC)
Hello,

tested the script and it worked nicely.

Encountered a problem on one PC that restarted automatically after uninstalling.
Is it possible to add a "norestart" or something similar to the uninstall option?


Thanks and Regards!
PeterG
#3PeterG Member Posts: 104  
posted: 5/19/2015 2:23:32 PM(UTC)
when i run on all of my pc's they don't restart, not sure why you had it restarting, Usually java installs and upgrades doesn't require restarts.
Kinetic
#4Kinetic Member Original PosterPosts: 4  
posted: 5/20/2015 9:43:20 AM(UTC)
Hi PeterG & hisax,

Thanks for the feedback - Given this seems to be getting a few hits, I've updated to address your issues.

PeterG please note, to ensure Java version 6 and below remain, you will want to change line 11 from:

$UninstallJava6andBelow = $true
to
$UninstallJava6andBelow = $false


Cheers! I've tested and works fine on my end - hopefully still working nicely for you all!

hisax
#5hisax Member Posts: 2  
posted: 5/20/2015 9:46:39 AM(UTC)
Thanks for the quick update.

Will report if there are any problems.

Regards!
ryancarter
#6ryancarter Member Posts: 4  
posted: 7/27/2015 10:24:06 PM(UTC)
I am seeing this error when running the script as an admin locally on a workstation.

PS C:\itcu> .\Remove_old_java_versions.ps1
Cannot index into a null array.
At C:\itcu\Remove_old_java_versions.ps1:71 char:35
+ $appGUID = $app.Properties[ <<<< "IdentifyingNumber"].Value.ToString()
+ CategoryInfo : InvalidOperation: (IdentifyingNumber:String) [], RuntimeException
+ FullyQualifiedErrorId : NullArray


Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
0 2 324 112 3 0.00 3588 msiexec
Cannot index into a null array.
At C:\itcu\Remove_old_java_versions.ps1:80 char:35
+ $appGUID = $app.Properties[ <<<< "IdentifyingNumber"].Value.ToString()
+ CategoryInfo : InvalidOperation: (IdentifyingNumber:String) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

0 2 328 116 3 0.00 2064 msiexec
Kinetic
#7Kinetic Member Original PosterPosts: 4  
posted: 7/28/2015 9:46:26 AM(UTC)
Hey ryancarter,

Updated with bug fixes, now version 1.2 - can you please see if this resolved your issues.

Cheers!
steefLCSO
#8steefLCSO Member Posts: 2  
posted: 8/24/2015 1:09:10 PM(UTC)
Hi Kinetec,

I think your script works fine.
I only get the following error message in my lansweeper deployment log: Result: Package timeout reached. . Timeout: (300Sec).
Do you have any idea how to fix this issue ?

Regards
PeterG
#9PeterG Member Posts: 104  
posted: 8/24/2015 4:12:45 PM(UTC)
try increasing package execution time from 15min to 30min and see if still doesn't work. You will also get package execution timeout if the package started and never got reply from client to server that is done due to network connection loss.
steefLCSO
#10steefLCSO Member Posts: 2  
posted: 8/26/2015 1:33:13 PM(UTC)
Hi PeterG,

Sadly it did not work for me, even with the increase the package execution time.
The same warning appears Package timeout reached. . Timeout: (900Sec).
Might this be a permisson problem ?

Cheers
laurin1
#11laurin1 Member Posts: 34  
posted: 11/7/2015 3:05:26 PM(UTC)
I need to also remove the old JDK versions. Any tips on how to modify this before I spend a bunch of time figuring it out on my own.
sarawitherow
#12sarawitherow Member Posts: 3  
posted: 11/18/2015 11:09:11 PM(UTC)
Great script. Just have one issue to ask about.

On our 64-bit machines, we have both the 32-bit Java and the 64-bit Java installed as it helps with some of our business applications.

The script run on a 64-bit machine only uninstalls the 64-bit Java. Is there an easy modification to have it remove the 32-bit as well?

Thanks,
Sara
PeterG
#13PeterG Member Posts: 104  
posted: 11/18/2015 11:12:06 PM(UTC)
it should remove both.. 32 and 64 bit.. it does on our pc's .. 99% of them are win7 64bit and works without issues.. there might be something else going on on yours.
sarawitherow
#14sarawitherow Member Posts: 3  
posted: 11/18/2015 11:26:25 PM(UTC)
I think I know. It seems the logic of the script is to check the versions on the machine, see which one has the highest value, and remove any of the items below that value.

My method of updating machines is to first remove all the older versions, then install the new update. So in this scenario, the latest would have to first be installed.

I would love a version that I could feed it the "new version" to the script so that it does remove all the older ones first.

sarawitherow
#15sarawitherow Member Posts: 3  
posted: 11/18/2015 11:57:24 PM(UTC)
I modified the script to have a value passed at the command line of the version of Java that will not be uninstalled.

Sometimes our users will update their Java past the company approved version that has been tested to be fully compatible with our Oracle business applications. So with this modification, it will remove all versions except for the version I feed the script - both older and newer.

Works great. Thanks!
:)
Sara
DanielB
#16DanielB Member Posts: 5  
posted: 12/10/2015 10:48:11 AM(UTC)
thx for the nice script ;)

I use it after installing the newest version.

But we also have the problem that it doesn't uninstall 32bit versions on 64bit machines.
For testings I installed an older 64bit version that got uninstalled with the script, but the 32bit version stayed.

Thanks,
Daniel
Ruben1
#17Ruben1 Member Posts: 16  
posted: 12/10/2015 11:49:19 AM(UTC)
@Daniel: I noticed this is normal behavior. I will always leave the latest version of the 32bit AND the latest version of the 64bit. In order to remove the older 32bit, you also need to install the new version of the 32bit.
norbertogomes
#18norbertogomes Member Posts: 3  
posted: 2/2/2016 2:28:44 PM(UTC)
I have the lasted JavaVersion: 8u71 and I would like to know if these scripts are compatible to remove older versions.
When I run the script, the machine restarts twice but all previous version still installed !

See the log below:

Result: Package timeout reached. Task Error: The task is currently running. Timeout: (300Sec). Credential: ("DOMAIN\user). ShareCredential: (server\user).
Machine has:
Java 8 update 51
Java 8 update 65
Java 8 update 66
Java 8 update 71 (lasted version)

tks !
Ruben1
#19Ruben1 Member Posts: 16  
posted: 2/2/2016 2:41:18 PM(UTC)
Still works fine here on Java 8 update 71.
PeterG
#20PeterG Member Posts: 104  
posted: 2/2/2016 3:58:43 PM(UTC)
as long as the naming string hasn't changed it should work
norbertogomes
#21norbertogomes Member Posts: 3  
posted: 2/4/2016 5:32:54 PM(UTC)
I deployed the package in a single Windows 7 desktop client and I enabled it to run powershell script but still not working.
All java versions are installed yeat!

See if the script attached is correctly !
Handles attachments
Gdsmcksysadmin
#22Gdsmcksysadmin Member Posts: 1  
posted: 2/7/2017 8:07:10 PM(UTC)
do you have a way to do it in mass? I am looking to run the script on 20-30 pc's
EleaCarm
#23EleaCarm Member Posts: 3  
posted: 4/21/2017 2:54:44 PM(UTC)
I had problems with PowerShell 1 and Windows 10 for 2 reasons:

1. The execution security of powershell is restricted "Get-ExecutionPolicy" and the script does not correctly convert the string to the question.

Fixed by executing "Set-ExecutionPolicy -ExecutionPolicy Unrestricted"


2. The question in the script:

If (($ app.Version -ne $ newest64bitVersion) -and ($ newest64bitVersion -ne $ null)) {

I do not operate correctly because $ newest64bitVersion returns a collection of number and not a string. The line I operate correctly is:

If (("$ app.Version" -ne "$ newest64bitVersion") -and ($ newest64bitVersion -ne $ null)) {


3. As an alternative method, VBScript is executed, which is attached.
Handles attachments
Remove_old_java_versions.txt (3kb) downloaded 230 time(s).
PeterG
#24PeterG Member Posts: 104  
posted: 4/21/2017 3:32:24 PM(UTC)
now if you are using the .exe installer you can add switch that removed all old java versions for you automatically after install

I do it by installing first x86 and than x64 version with the (remove old java switch) and takes out all obsolete versions.


example "jre-8u131-windows-x64.exe" /s AUTO_UPDATE=0 EULA=0 NOSTARTMENU=1 SPONSORS=0 WEB_ANALYTICS=0 WEB_JAVA=1 WEB_JAVA_SECURITY_LEVEL=H REMOVEOUTOFDATEJRES=1"

Active Discussions

Lansweeper Laptop warranty include users from active directory filtered by OU
by  Iyad   Go to last post Go to first unread
Last post: Yesterday at 11:09:27 PM(UTC)
Lansweeper Exclude Search
by  pryan67  
Go to last post Go to first unread
Last post: Yesterday at 4:01:43 PM(UTC)
Lansweeper Report: All Apple Mac devices with Memory RAM asset
by  gabrielo   Go to last post Go to first unread
Last post: Yesterday at 3:17:24 PM(UTC)
Lansweeper Does technical support for LS really respond?
by  tosch  
Go to last post Go to first unread
Last post: Yesterday at 12:48:50 PM(UTC)
Lansweeper Deployment packages using lsagent
by  CyberCitizen   Go to last post Go to first unread
Last post: 6/15/2021 11:44:33 PM(UTC)
Lansweeper INFO DateTimeService time refresh
by  ZachO21  
Go to last post Go to first unread
Last post: 6/15/2021 4:23:15 PM(UTC)
Lansweeper Helpdesk tabs always regenarated
by  Carla   Go to last post Go to first unread
Last post: 6/14/2021 9:49:27 PM(UTC)
Lansweeper Importing with user relations
by  teddyh2o  
Go to last post Go to first unread
Last post: 6/14/2021 6:05:46 PM(UTC)