MRed
MRed

Reputation: 1

Uninstalling updates using wusa.exe

I am trying to write a powershell script which uninstalls updates.

My problem is that the script doesn't run the wusa.exe when starting the script.

function Uninstall-Hotfix () {
    [string]$parameters = "KB4041691"
    [string]$KBs = @()

    if ($parameters.Contains(":")) {
        [object]$arguments = $parameters.Split(":")
        foreach ($argument in $arguments) {
            $argument.Replace("KB", "")
            $KBs.add($argument)

            for ($i = 0; $i -lt $KBs.length; $i++) {
                Cmd /c wusa.exe /uninstall /KB:$KBs[$i] /quiet /norestart
                Do {
                    Start-Sleep -Seconds 3
                }
                while (Wait-Process | Where-Object {$_.name -eq "wusa"}) 

                If (Get-Hotfix -Id $KBs[$i] -ErrorAction SilentlyContinue) {
                    Write-Host "KB $KBs[$i] Fehlerhaft"
                }
                Else {
                    Write-Host "KB $KBs[$i] Erfolgreich deinstalliert"
                }
            }
        }
    }
    Else {
        $parameter = $parameters.Replace("KB", "")
        $parameter
        cmd /c wusa.exe /uninstall /KB:$parameter /quiet /norestart
        Do {
            Start-Sleep -Seconds 3
        }
        while (Wait-Process | Where-Object {$_.name -eq "wusa.exe"})
    }
}
Uninstall-Hotfix

Upvotes: 0

Views: 2210

Answers (1)

Manu
Manu

Reputation: 1742

Your code is very heavy and in my opinion contains too much loops, you can try this :

function Uninstall-Hotfix () {
    Param(
        [Parameter(Mandatory=$true)][array]$Patches
    )

    foreach($patch in $Patches){
        $numKb = $null
        if($patch -match "\d{7}"){
            [int]$numkb = $Matches[0]
            Write-Host $numKb

            Start-Process wusa.exe -ArgumentList "/KB:$numKb /uninstall /quiet /norestart" -Wait

            if(Get-Hotfix -Id $numKb -ErrorAction SilentlyContinue){
                Write-Host "KB $KBs[$i] Fehlerhaft"
            }
            else{
                Write-Host "KB $KBs[$i] Erfolgreich deinstalliert"
            }
        }
        else{
            Write-Host "KB is not valid"
        }
    }
}
Uninstall-Hotfix -Patches KB4041691,KB1234567

Upvotes: 1

Related Questions