通过Powershell IndexOutOfRangeException进行的Windows Update



我正试图通过PowerShell使用WUApi中的COM对象安装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:UsersMyUserDocumentsUpdate-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://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1#检查空

最新更新