I am using this script to uninstall software (eg. Java). However, I have two Java packages, Java 8 Update and Java Auto Updater, on my machine.
I understand that when I run my script on such a machine that has two software that match my Regex (Java* in this case), it fails to make a $classkey that is unique to remote machine's WMI and so is the case it breaks.
function Uninstall-Application($computer, $target) {
$productInfo = Get-WmiObject Win32_Product -Filter "Name LIKE '%$target%'" -ComputerName $computer
$pin = $productInfo.IdentifyingNumber
$pn = $productInfo.Name
$pv = $productInfo.Version
if ($pn -ne $null) {
for ($i = 0; $i -lt $Productinfo.length; $i++) {
$classKey = "IdentifyingNumber=`"$pin[$i]`",Name=`"$pn[$i]`",version=`"$pv[$i]`""
$uninstallReturn = ([wmi]"\\$computer\root\cimv2:Win32_Product.$classKey").uninstall()
if ($uninstallReturn.ReturnValue -ge 0) { Write-Host "Uninstall complete"}
else { $uninstallReturn | Out-Host }
}
}
else {
Throw "Product not found"
}
}
uninstall-application "RemoteServer" "Java"
This code works, If there is just one software that matches my regex.