0

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.

1 Answer 1

1

You can use a foreach loop to run the uninstall code against multiple items.

$products = Get-WmiObject Win32_Product -Filter "Name LIKE '%$target%'" -ComputerName $computer
foreach ($productInfo in $products) {
    #uninstall code
}

Full function:

function Uninstall-Application($computer, $target) {
    $products = Get-WmiObject Win32_Product -Filter "Name LIKE '%$target%'" -ComputerName $computer
    foreach ($productInfo in $products) {
        $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 "localhost" "Java"
Sign up to request clarification or add additional context in comments.

2 Comments

OK, so uncomment the three lines to make the uninstall works?
Yep, there's no -WhatIf for that WMI command so I left it commented out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.