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

PowerShell脚本多输出问题修复:KB补丁安装状态检测需求实现

问题分析
  • 多余输出:脚本中$installed.HotFixID是直接输出语句,会打印匹配到的补丁ID,导致额外结果。
  • 命令过时:Get-WmiObject已被Get-CimInstance替代,后者性能更好且适配现代PowerShell版本。
  • 空值报错风险:未找到补丁时$installed为null,此时访问$installed.HotFixID会抛出错误。
  • 匹配逻辑不精准:-Match是正则匹配,可能误匹配包含目标KB编号的其他补丁,应该用精确匹配-eq。
  • 冗余操作:Invoke-WebRequest会自动创建目标文件,无需提前用New-Item;Remove-Item针对单个文件时,-Recurse参数多余。
修正后的脚本
$appArray = @(
    @{
        App         = 'kb5017024'
        App_source  = 'https://catalog.s.download.windowsupdate.com/d/msdownload/update/software/secu/2022/08/windows10.0-kb5017024-x64-ndp48_f2a8bd55b98a9cabc5a8b6179f619165b29c8273.msu'
        Destination = "c:\temp\kb5017024.msu"
        Argument    = '/S'
    },
    @{
        App         = 'kb5012170'
        App_source  = 'https://catalog.s.download.windowsupdate.com/d/msdownload/update/software/secu/2022/08/windows10.0-kb5012170-x64_0558b5879de03bfb5319b1244d84ca3735a6a377.msu'
        Destination = "c:\temp\kb5012170.msu"
        Argument    = '/norestart /qn'
    }
)

# 确保临时目录存在
if (-not (Test-Path "c:\temp")) {
    New-Item -ItemType Directory -Path "c:\temp" -Force | Out-Null
}

foreach ($app in $appArray) {
    # 精确检查补丁是否已安装
    $installed = Get-CimInstance Win32_QuickFixEngineering | Where-Object { $_.HotFixID -eq $app.App }

    if ($installed) {
        Write-Host "$($app.App) 已安装。"
    }
    else {
        # 下载补丁
        Invoke-WebRequest -Uri $app.App_source -OutFile $app.Destination -PassThru | Out-Null
        
        # 安装补丁
        Start-Process -FilePath $app.Destination -ArgumentList $app.Argument -Wait
        
        # 删除安装文件
        Remove-Item -Path $app.Destination -Force
    }
}
修正说明
  • 移除多余的$installed.HotFixID输出语句,消除额外结果。
  • 替换为Get-CimInstance命令,提升脚本兼容性与性能。
  • 简化已安装检查逻辑:直接判断$installed是否存在,避免空值访问错误,同时用-eq确保精确匹配。
  • 添加临时目录检查,避免下载时因路径不存在报错。
  • 移除冗余的文件创建步骤,简化脚本流程。
  • 调整Remove-Item参数,用-Force确保文件删除,去掉不必要的-Recurse。
  • 用Out-Null屏蔽命令的冗余输出,让脚本输出更简洁。

内容的提问来源于stack exchange,提问作者Sagar Mahto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:50:37