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.