You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

批量Windows服务器更新PowerShell脚本需求及现有脚本故障解决

多Windows服务器批量安装安全/关键更新的PowerShell脚本修复方案

原脚本存在的问题

  • 未做依赖检查:Get-WindowsUpdate和Install-WindowsUpdate属于第三方模块PSWindowsUpdate,Windows默认未预装,直接执行会报错
  • 无多服务器支持:原脚本仅能在本地运行,无法批量处理多台服务器
  • 集合参数错误:$updates是更新对象集合,直接传递$updates.KBArticleID可能触发参数绑定异常,需正确提取KB编号

修复后的完整脚本

# 配置目标服务器列表,替换为你的服务器名称或IP
$targetServers = @("Server01", "Server02", "Server03")

# 检查并安装PSWindowsUpdate模块(本地执行一次即可)
if (-not (Get-Module -ListAvailable -Name PSWindowsUpdate)) {
    Install-Module -Name PSWindowsUpdate -Force -AllowClobber -Scope CurrentUser
}

# 遍历每台服务器执行更新操作
foreach ($server in $targetServers) {
    Write-Host "`n=== 开始处理服务器: $server ===" -ForegroundColor Cyan

    try {
        # 建立远程PowerShell会话
        $session = New-PSSession -ComputerName $server -ErrorAction Stop
        
        # 远程检测关键/安全更新
        $updates = Invoke-Command -Session $session -ScriptBlock {
            Get-WindowsUpdate -Classification "Critical,Security" -ErrorAction Stop
        }

        if ($updates.Count -eq 0) {
            Write-Host "服务器 $server 暂无需要安装的关键/安全更新" -ForegroundColor Green
            Remove-PSSession $session
            continue
        }

        Write-Host "服务器 $server 检测到 $($updates.Count) 个待安装更新,开始安装..." -ForegroundColor Yellow
        
        # 远程安装更新,可根据需求调整参数
        $installResult = Invoke-Command -Session $session -ScriptBlock {
            param($kbIDs)
            Install-WindowsUpdate -KBArticleID $kbIDs -AcceptAll -AutoReboot -ErrorAction Stop
        } -ArgumentList $updates.KBArticleID

        Write-Host "服务器 $server 更新安装完成,结果: $($installResult.Result)" -ForegroundColor Green
    }
    catch {
        Write-Host "服务器 $server 处理失败: $($_.Exception.Message)" -ForegroundColor Red
    }
    finally {
        # 确保关闭远程会话
        if ($session) { Remove-PSSession $session }
    }
}

Write-Host "`n所有服务器处理完成" -ForegroundColor Cyan

使用说明

  • 替换$targetServers中的内容为实际需要处理的服务器名称或IP地址
  • 执行脚本的账号必须拥有所有目标服务器的管理员权限
  • 首次运行需允许PowerShell执行脚本:在PowerShell中执行Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
  • 可调整Install-WindowsUpdate的参数:比如去掉-AutoReboot避免自动重启,添加-IgnoreReboot忽略重启提示

内容的提问来源于stack exchange,提问作者Iman Jafari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:42:40