Windows Update via Powershell IndexOutOfRangeException

517 Views Asked by At

I am trying to install windows updates via PowerShell making use of COM objects from WUApi.

Here's the code I have got so far.

$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()

When I run this code, I get 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

I have checked and double checked and I can't seem to find where the issues is. I have tried similar logic with a C# code and that seems to be able assign the Updates variable fine without any issues.

Any idea what I am missing here? Thanks in advance.

2

There are 2 best solutions below

1
swbbl On

Can't reproduce but am pretty sure that "$updateResult.Updates" is $null (= no updates available) Can you please check?

If so, add an if condition ($null on the left side when used with collections!)

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

Why $null on the left? (regardless of PS version): https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1#checking-for-null

1
Rogerio On

Try it:

$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"
}