title: Install windows update
body: <p>I have following powershell script which should update my windows OS everytime I run it. Therefore I use the given windows API in order to search, download and install the updates. But somehow only searching for them actually works.</p>
  
  <p>This is my script:</p>
  
  <pre><code>$global:scriptpath = $MyInvocation.MyCommand.Path
  $global:dir = Split-Path $scriptpath
  $global:logfile = "$dir\updatelog.txt"
  
  write-host " Searching for updates..."
  $session = New-Object -ComObject Microsoft.Update.Session
  $searcher = $session.CreateUpdateSearcher()
  $result = $searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
  
  if ($result.Updates.Count -eq 0) {
       Write-Host "No updates to install"
  } else {
  
      $result.Updates | Select Title
  
  }
  
  $downloads = New-Object -ComObject Microsoft.Update.UpdateColl
  
  foreach ($update in $result){
      try {
          $update.AcceptEula()
          $Null = $downloads.Add($update)
      } catch {}
  
  }
  
  $count = $result.Updates.Count
  
  write-host ""
  write-host "There are $($count) updates available."
  write-host ""
  
  read-host "Press Enter to download\install updates"
  
  $downloader = $session.CreateUpdateDownLoader()
  $downloader.Updates = $downloads
  $downloader.Download()
  
  $installs = New-Object -ComObject Microsoft.Update.UpdateColl
  foreach ($update in $result.Updates){
       if ($update.IsDownloaded){
             $installs.Add($update)
       }
  }
  
  $installer = $session.CreateUpdateInstaller()
  $installer.Updates = $installs
  $installresult = $installer.Install()
  $installresult
  </code></pre>
  
  <p>But I get following error:</p>
  
  <pre><code>Exception calling "Download" with "0" argument(s): "Exception from HRESULT: 0x80240024"
  + $downloader.Download()
  + ~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ComMethodTargetInvocation
  </code></pre>
  
  <p>Somehow this line: $downloader.Updates = $downloads is not executed, but I don't know why. I also already tried running the script as an admin, didn't work either.</p>