Reputation: 43
I've wrote a PowerShell script to check for Java version and if it's not there it will run the installer for it, but for some reason even though it detects the specified Java version yet it still run the installer.
$java = Get-WmiObject -Class win32_product |
where {$_.Name -like "*Java 7 Update 80*"}
If ($java -eq 'Java 7 Update 80') {
"your java version is acceptable"
Exit
} ElseIf ($java -ne 'Java 7 Update 80') {
Start-Process -filepat C:\jre1.7.0_80.msi /passive
"You don't have the right version of Java, installing Java 7 Update 80"
}
Write-Host "End"
Upvotes: 0
Views: 3032
Reputation: 1052
You filter with -like "*Java 7 Update 80*"
, which will pick up more than just Java 7 Update 80
(for instance Java 7 Update 80 (64-bit)
), but then check if the returned string is exactly Java 7 Update 80
when you decide whether or not to launch the installer.
Do as @Random says and check the value of $java
before the If
. You most likely have something similar too, but more than just "Java 7 Update 80" in $java
.
To avoid this kind of flaky behavior you need to keep your conditions consistent. Either use -like "*Java 7 Update 80*"
everywhere, or use -eq "Java 7 Update 80"
everywhere, but don't mix them.
You could also make use of how PowerShell evaluates other types to boolean. Your Get-WmiObject
statement produces either $null
(which evaluates to $false
) or a non-empty string (which evaluates to $true
), so you could do something like this to avoid implementing the same check multiple times:
if ($java) {
"your java version is acceptable"
Exit
} else {
Start-Process -filepat C:\jre1.7.0_80.msi /passive
"You don't have the right version of Java, installing Java 7 Update 80"
}
You don't need an elseif
condition anyway, since your logic is binary (Java either is or isn't installed).
Upvotes: 1
Reputation: 43
So turned out that the $java variable was wrong, also Eric was right
Start-Process powershell -Verb runAs
$java = Get-WmiObject -Class win32_product | where { $_.Name -like "*Java 7 Update 71*"}
If ($java){"your java version is acceptable"}
Else {Start-Process "C:\jre-7u71-windows-i586.exe" -Verb runAs -ArgumentList "/s" -Wait
"You don't have the right version of Java, installing Java 7 Update 71"
}
Write-Host "Press any key to exit..."
Upvotes: 0