0

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.

Kumar
  • 113
  • 1
  • 10
  • Unable to duplicate. It worked fine for me. – Doug Maurer Nov 12 '20 at 04:58
  • I did try again today and it doesn't happen any more. I think may be a machine restart may have fixed this issue. Think it may have been triggered due to a COM object memory leak. Thanks for the response anyways. – Kumar Nov 19 '20 at 01:14

1 Answers1

0

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

swbbl
  • 814
  • 1
  • 4
  • 10
  • Thanks for the response. Think a restart to the machine has fixed this issue for me. Could be some COM memory leak which may have triggered this? – Kumar Nov 19 '20 at 01:16