使用wusa.exe

时间:2017-10-19 11:50:11

标签: powershell windows-update

我正在尝试编写一个卸载更新的powershell脚本。

我的问题是脚本在启动脚本时没有运行wusa.exe

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

1 个答案:

答案 0 :(得分:0)

您的代码非常繁重,在我看来包含太多循环,您可以试试这个:

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