> ## Content Index
> Fetch the complete content index at: https://note.xdq.me/llms.txt
> Use this file to discover other available public pages before exploring further.

# Powershell 操作 windows更新
- URL: https://note.xdq.me/powershell-cao-zuo-windowsgeng-xin/
- Published: 2019-07-08T06:24:28.000Z
- Updated: 2026-10-03T02:58:57.000Z
- Author: xud6
- Tags: powershell, windows, #Import 2026-10-03 02:45

## 定义更新搜索

```
$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")
}

```