Search code examples
powershellpowercli

Automating WSUS updates with PowerShell/PowerCLI


I'm looking to automate the process of installing WSUS updates on my VMs. To give a short overview, here are the things I want to accomplish (please let me know if my methods are moronic, I'd love to learn the right way for all of this.):

  • Check if the particular VM has any WSUS updates to install
  • If there are updates available, take a snapshot of the VM
  • Begin the WSUS install
  • Reboot the system, if necessary

I am currently able to check if the particular VM has updates and take a snapshot. Now I know I could just have this portion of the script run and configure a GPO to accomplish the rest of the tasks, but my thought process is that if I can do it all in the script, I will be able to check that the snapshot of the VM exists prior to installing the update. Below you can see what my script does as of now.

foreach ($vm in $vms) {
   if ($vm.PowerState -eq "poweredOn") {
      $output = Invoke-VMScript -ScriptText $script -VM $vm -GuestCredential $guestCred
      if ($output.ScriptOutput -Notlike '0*') {
         New-Snapshot -VM $vm -Name BeforeWSUS
      }
   }
}

After this I would like to perform a check to see if the snapshot exists for a vm, then install the WSUS update. If a reboot is necessary, then reboot.

Is there a way to do this? A better way to do this? Would really appreciate some insight, I'm new to Powershell.

Edit: I've checked on the PSWindowsUpdate Module, would that need to be on each VM I plan to update?


Solution

  • Yes, you would need PSWindowsUpdate installed on each VM.

    You could include something like this in your script to check if PSWindowsUpdate is installed and if not, install it.

    Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
    $Modules = "PSWindowsUpdate"
    $Modules | ForEach-Object {
        If (!(Get-Module -ListAvailable -Name $_)) {
                Install-Module $_ -Verbose -Confirm:$false
        }
    }
    

    I think that Install-Module requires PowerShell version 5.0.

    Then you would use Get-WUInstall to install updates from your WSUS server. (It looks like it defaults to WSUS if configured via GPO.)

    Probably throw in a -Confirm:$False to avoid it prompting you to allow each update.

    More info on PSWindowsUpdate: https://github.com/joeypiccola/PSWindowsUpdate