通过Powershell IndexOutOfRangeException进行Windows更新

问题描述

我正在尝试使用WUApi中的COM对象通过PowerShell安装Windows更新。

这是我到目前为止获得的代码

$updateSession = New-Object -com Microsoft.update.Session
$updateSearcher = $UpdateSession.CreateUpdateSearcher()
$updateResult = $updateSearcher.Search("IsInstalled=0 and Type='Software'");
$needsRestart = $false
foreach($update in $updateResult.Updates) {
    $needsRestart = $needsRestart -or $update.InstallationBehavior.RebootBehavior -ne 0
}
$updateDownloader = $UpdateSession.CreateUpdateDownloader()
$updateDownloader.Updates = $updateResult.Updates
$downloadResult = $updateDownloader.Download()

运行此代码时,我得到IndexOutOfRangeException

Index was outside the bounds of the array.
At C:\Users\MyUser\Documents\Update-Windows2.ps1:9 char:1
+ $updateDownloader.Updates = $updateResult.Updates
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [],IndexOutOfRangeException
    + FullyQualifiedErrorId : system.indexOutOfRangeException

我已经检查并再次检查,但似乎找不到问题所在。我已经使用C#代码尝试了类似的逻辑,并且似乎可以毫无问题地分配Updates变量。

知道我在这里缺少什么吗?预先感谢。

解决方法

无法重现,但可以确定“ $ updateResult.Updates”为$ null(=无可用更新) 你能检查一下吗?

如果是这样,请添加if条件(与集合一起使用时,左侧为$ null!)

if ($null -ne $updateResult.Updates) {
    $updateDownloader.Updates = $updateResult.Updates
    $downloadResult = $updateDownloader.Download()
}

为什么$ null在左边? (与PS版本无关): https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1#checking-for-null