通过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变量。

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)