Windows补丁检查与安装脚本

代码脚本 · Windows

检查Windows系统补丁更新状态,列出已安装和待安装的补丁,支持自动下载安装关键更新,生成补丁报告,适用于Windows Server和Windows 10/11

详细内容

<# .SYNOPSIS Windows补丁检查与安装脚本 .DESCRIPTION 检查Windows更新状态,列出待安装补丁,支持自动安装关键更新 .USAGE .\windows_update_check.ps1 # 仅检查 .\windows_update_check.ps1 -Install # 检查并安装 #> param( [switch]$Install, # 是否自动安装更新 [switch]$Reboot, # 安装后是否自动重启 [string]$ReportPath = "C:\Windows\Temp\windows_update_report_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt" ) # 检查管理员权限 $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Host "⚠️ 建议以管理员身份运行此脚本" -ForegroundColor Yellow } Write-Host "==========================================" -ForegroundColor Cyan Write-Host " Windows补丁检查工具" -ForegroundColor Cyan Write-Host " 计算机: $env:COMPUTERNAME" -ForegroundColor Cyan Write-Host " 时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Cyan Write-Host "==========================================" -ForegroundColor Cyan # 系统信息 Write-Host "`n【系统信息】" -ForegroundColor Yellow $os = Get-CimInstance Win32_OperatingSystem Write-Host " 操作系统: $($os.Caption) $($os.Version)" Write-Host " 架构: $($os.OSArchitecture)" Write-Host " 上次启动: $($os.LastBootUpTime)" Write-Host " 运行时长: $([math]::Floor((Get-Date) - $os.LastBootUpTime).TotalDays)天" # 使用Windows Update COM对象检查更新 Write-Host "`n【检查可用更新】" -ForegroundColor Yellow Write-Host " 正在搜索更新,请稍候..." try { $UpdateSession = New-Object -ComObject Microsoft.Update.Session $UpdateSearcher = $UpdateSession.CreateUpdateSearcher() $SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0") $updates = $SearchResult.Updates $criticalCount = ($updates | Where-Object { $_.MsrcSeverity -eq "Critical" -or $_.MsrcSeverity -eq "Important" }).Count $optionalCount = $updates.Count - $criticalCount Write-Host " 可用更新总数: $($updates.Count)" -ForegroundColor White Write-Host " 关键/重要更新: $criticalCount" -ForegroundColor Red Write-Host " 可选更新: $optionalCount" -ForegroundColor Gray if ($updates.Count -eq 0) { Write-Host "`n✅ 系统已是最新,没有待安装的更新" -ForegroundColor Green } else { Write-Host "`n【待安装更新列表】" -ForegroundColor Yellow $i = 1 foreach ($update in $updates) { $severity = if ($update.MsrcSeverity) { $update.MsrcSeverity } else { "未知" } $severityColor = switch ($severity) { "Critical" { "Red" } "Important" { "DarkRed" } "Moderate" { "Yellow" } default { "Gray" } } Write-Host " $i. [$severity] $($update.Title)" -ForegroundColor $severityColor Write-Host " KB: $($update.KBArticleIDs -join ', ') | 大小: $([math]::Round($update.MaxDownloadSize/1MB, 1))MB" $i++ } # 安装更新 if ($Install) { Write-Host "`n【开始安装更新】" -ForegroundColor Yellow Write-Host " 正在下载并安装更新,这可能需要较长时间..." $UpdatesToDownload = New-Object -ComObject Microsoft.Update.UpdateColl foreach ($update in $updates) { if ($update.EulaAccepted -eq $false) { $update.AcceptEula() | Out-Null } $UpdatesToDownload.Add($update) | Out-Null } # 下载 $Downloader = $UpdateSession.CreateUpdateDownloader() $Downloader.Updates = $UpdatesToDownload Write-Host " 正在下载 $($UpdatesToDownload.Count) 个更新..." $DownloadResult = $Downloader.Download() Write-Host " 下载完成,结果代码: $($DownloadResult.ResultCode)" # 安装 $UpdatesToInstall = New-Object -ComObject Microsoft.Update.UpdateColl foreach ($update in $updates) { if ($update.IsDownloaded) { $UpdatesToInstall.Add($update) | Out-Null } } if ($UpdatesToInstall.Count -gt 0) { $Installer = $UpdateSession.CreateUpdateInstaller() $Installer.Updates = $UpdatesToInstall Write-Host " 正在安装 $($UpdatesToInstall.Count) 个更新..." $InstallResult = $Installer.Install() Write-Host " 安装完成,结果代码: $($InstallResult.ResultCode)" Write-Host " 需要重启: $($InstallResult.RebootRequired)" if ($InstallResult.RebootRequired -and $Reboot) { Write-Host " 10秒后自动重启..." -ForegroundColor Red Start-Sleep -Seconds 10 Restart-Computer -Force } elseif ($InstallResult.RebootRequired) { Write-Host "`n⚠️ 需要重启计算机才能完成更新安装" -ForegroundColor Yellow } } } else { Write-Host "`n💡 如需自动安装,请运行: .\windows_update_check.ps1 -Install" -ForegroundColor Cyan } } } catch { Write-Host "❌ 检查更新失败: $($_.Exception.Message)" -ForegroundColor Red Write-Host " 请确保Windows Update服务正在运行" -ForegroundColor Gray } # 已安装更新历史 Write-Host "`n【最近安装的10个更新】" -ForegroundColor Yellow try { $installed = Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10 foreach ($hf in $installed) { Write-Host " $($hf.InstalledOn.ToString('yyyy-MM-dd')) | $($hf.HotFixID) | $($hf.Description)" } } catch { Write-Host " 无法获取已安装更新列表" -ForegroundColor Gray } # 生成报告 Write-Host "`n【报告已保存到】$ReportPath" -ForegroundColor Cyan "Windows补丁检查报告" | Out-File $ReportPath -Encoding UTF8 "计算机: $env:COMPUTERNAME" | Out-File $ReportPath -Encoding UTF8 -Append "时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File $ReportPath -Encoding UTF8 -Append "可用更新数: $($updates.Count)" | Out-File $ReportPath -Encoding UTF8 -Append Write-Host "`n==========================================" -ForegroundColor Cyan Write-Host " 检查完成" -ForegroundColor Cyan Write-Host "==========================================" -ForegroundColor Cyan

适配环境

适配系统:Windows 10+,Windows Server 2016+

依赖环境:Windows PowerShell 5.1+

参数说明

[{"name": "Install", "label": "\u662f\u5426\u81ea\u52a8\u5b89\u88c5\u66f4\u65b0(true/false)", "default": "false"}, {"name": "Reboot", "label": "\u5b89\u88c5\u540e\u662f\u5426\u81ea\u52a8\u91cd\u542f(true/false)", "default": "false"}]
Windows补丁更新PowerShell安全

更多Windows