Powershell 操作 windows更新

 •  Filed under powershell, windows

定义更新搜索

$Criteria = "IsInstalled=0 and Type='Software'"

搜索可用的更新

$Searcher = New-Object -ComObject Microsoft.Update.Searcher
$SearchResult = $Searcher.Search($Criteria).Updates

下载更新

$Session = New-Object -ComObject Microsoft.Update.Session
$Downloader = $Session.CreateUpdateDownloader()
$Downloader.Updates = $SearchResult
$Downloader.Download()

安装更新

$Installer = New-Object -ComObject Microsoft.Update.Installer
$Installer.Updates = $SearchResult
$Result = $Installer.Install()

检查是否需要重启

$Result.rebootRequired

PS脚本

function log($str){
    Write-Host $str
}

#Define update criteria.
$Criteria = "IsInstalled=0 and Type='Software'"

#Search for relevant updates.
$Searcher = New-Object -ComObject Microsoft.Update.Searcher
$SearchResult = $Searcher.Search($Criteria).Updates
$MissingPatches = @($SearchResult).length
log("$($MissingPatches) patches found")
$SearchResult | select Title,IsBeta,IsHidden,IsInstalled,MsrcSeverity | Format-Table -AutoSize

if($MissingPatches -gt 0){
    #Download updates.
    log("download updates")
    $Session = New-Object -ComObject Microsoft.Update.Session
    $Downloader = $Session.CreateUpdateDownloader()
    $Downloader.Updates = $SearchResult
    $Downloader.Download()

    #Install updates.
    log("install updates")
    $Installer = New-Object -ComObject Microsoft.Update.Installer
    $Installer.Updates = $SearchResult
    $Result = $Installer.Install()

    $Result
    #Reboot if required by updates.
    if($Result.rebootRequired){
        log("Reboot required")
    }else{
        log("Reboot not required")
    }
}else{
    log("no patch found")
}