通过 Powershell IndexOutOfRangeException 进行 Windows 更新

问题描述 投票:0回答:2

我正在尝试使用 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
变量,没有任何问题。

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

windows powershell windows-update wuapi
2个回答
0
投票

无法重现,但我很确定“$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#checking-for-null


0
投票

尝试一下:

$updateSession = New-Object -com Microsoft.update.Session
$updateSearcher = $UpdateSession.CreateUpdateSearcher()
$updateResult = $updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0").Update
$needsRestart = $false

If ($updateResult.Updates.Count -ne 0){
    foreach($update in $updateResult.Updates) {
        $needsRestart = $needsRestart -or $update.InstallationBehavior.RebootBehavior -ne 0
    }

    $updateDownloader = $UpdateSession.CreateUpdateDownloader()
    $updateDownloader.Updates = $updateResult.Updates
    $downloadResult = $updateDownloader.Download()
}
Else{
    Write-Host "No have updates available"
}
© www.soinside.com 2019 - 2024. All rights reserved.