How to use PowerShell to install Windows updates & ensure long-term compliance

by | May 22, 2023 | Tech Blog

Patch Tuesday Releases

Tech Blogs

Critical Patches

In this post I will walk you through how to install Windows updates and report on patch compliance using Windows PowerShell. We will be using:
  • kbupdate – a community Windows PowerShell module written by Chrissie LeMaire (SQL & PS MVP, GitHub Star, creator of dbatools)
  • wsusscn2.cab – a Microsoft Windows update offline file, regularly updated by Microsoft every Patch Tuesday
Firstly, no matter what tool you use, you should have a process in place to patch your systems. The threat of vulnerable software can be mitigated by installing updates if the software is still in support by the vendor. In 2022, IBM reported that 13% of data breaches was caused by vulnerabilities in third-party software used as the initial attack vector. There is no reason to believe vulnerable Operating Systems are any less of a threat. In fact, given the prevalence of Windows used in both clients and servers, it’s likely a more significant risk.

Why use PowerShell to Install Updates?

There is no shortage of patching solutions to manage Windows updates out there. However, orchestrating your own patching routines with code allows you to create a bespoke patching solution.

For example, you might have a complicated application server topology involving multiple Windows server hosts running a variety of services. Perhaps they need to shutdown/startup in a specific order or require custom pre/post actions for each step during your patching routine.

Tools do exist on the market that offer the flexibility to manage updates without code. However, to codify Windows update with PowerShell opens the door to limitless patching. You could use cloud services such as Azure Automation and Azure Arc to orchestrate these complex patching routines for your on-premises servers, too.

On the other hand, you might be a small business or have a small budget and can’t afford to buy such tools to patch just your endpoints. For this, you use Windows Task Scheduler to configure kbupdate to install only specific types of updates. This will give you more granular control of automatic updates using PowerShell code.

Manage Windows Update with kbupdate

kbupdate is a PowerShell module that can find, install, and uninstall Windows updates. One of its greatest features is that it can report what updates are missing on a Windows host that are not approved in a Windows Server Update Service (WSUS) server or any other Windows update patching solution.

Be sure to check out this YouTube recording from a live demo of kbupdate given by Chrissie at PsConfEU 2022 MiniCon!

At the time of writing this, kbupdate supports both Windows PowerShell 5.1 and PowerShell 7.2.

Before you start using kbupdate

Depending on your version of PowerShell, or if you are running an older Windows version than Windows 10 or Windows Server 2016, make sure you update to the latest Windows Management Framework 5.1 – Windows Management Framework (WMF) – PowerShell | Microsoft Learn.

Run the below in the PowerShell console to install the latest version of kbupdate from the PowerShell Gallery:

Install-Module kbupdate -Scope CurrentUser

Before I show you anything about this module, do not forget about Get-Help – generally, it is the best way to discover how to use cmdlets in PowerShell. For example, use the below to see all commands available in the module:
Get-Command -Module 'kbupdate'
The output of Get-Command to see all the available cmdlets in the kbupdate module

Also, use the below to see all the help information for a specific function:

Get-Help Get-KbNeededUpdate -Full

The output of Get-Help to see the help information of the cmdlet Get-KbNeededUpdate

Get-KbNeededUpdate

Let’s start with the Get-KbNeededUpdate function. This will show you the available updates missing on a system.
Get-KbNeededUpdate
The result of running Get-KbNeededUpdate on Windows 11 to identify missing updates

This code can take a while to run, especially if there are many updates to search through.

By default, if your Windows Update Agent is configured to report to a WSUS server, then it will scan against approved updates in WSUS. Otherwise, it will scan against Windows Update (aka the Microsoft update servers.)

If you want to forcefully scan against Windows Update, and not WSUS, use the -UseWindowsUpdate parameter.

Get-KbNeededUpdate -UseWindowsUpdate

NOTE: If running this command on an unpatched Windows 10 or 11 device to scan against your WSUS server, and:

  • the Windows 10 or 11 category is not enabled in WSUS, or
  • no Windows 10 or 11 updates are approved

Get-KbNeededUpdate will not show you any available updates.

If you get the error message Exception from HRESULT: 0x8024500C, this translates to “Connections to the redirector server are disallowed by managed policy”. It is likely because you have the Group Policy Object (GPO) Do not connect to any Windows Update Internet locations enabled and the device doesn’t report to a WSUS server.

Install-KbUpdate

Install-KbUpdate can be used in a variety of ways to install updates, but we’ll leverage the pipeline system of PowerShell by simply supplying the output from Get-KbNeededUpdate, straight into Install-KbUpdate, so we can automatically download and install all needed updates:

Get-KbNeededUpdate | Install-KbUpdate

The result of running Install-KbUpdate on Windows 11

Get-KbUpdate

This cmdlet can be used to query the Microsoft update catalogue for updates meeting a variety of criteria. We can retrieve a specific update by its article ID, or more generically by using other parameters such as -Architecture, -Pattern, or -OperatingSystem.
The result of Get-KbUpdate using the aforementioned parameters to search the Microsoft update catalogue database

Save-KbUpdate

In conjunction with Get-KbUpdate, we can also download Windows updates by using Save-KbUpdate. Much like we did before, we will leverage the pipeline system in PowerShell and feed the output from Get-KbUpdate to download specific updates.
Showing the console output and files on disk after saving updates to disk using Save-KbUpdate

Remote Computers

You can absolutely use kbupdate to install Windows updates at the command line on a local server, remote computer, or remote servers, too. You will see most of the commands sport a -ComputerName parameter. This will enable you to specify remote servers. kbupdate is a fantastic PowerShell module that makes light work of installing Windows updates. Without it, our options are limited to the PSWindowsUpdate PowerShell module, or the Windows Update Agent (WUA) API.

Reporting the Absolute Truth for Windows Update Compliance using PowerShell

Next, I want to talk about identifying missing Windows updates using PowerShell, but this time using the Windows Update offline scan file to tell you exactly what is missing. Scanning against just WSUS can be problematic. Later, I will talk more about this, but the offline scan file will help uncover gaps in your patching strategy. Microsoft provides the Windows Update offline scan file in the form of a .cab file – wsusscn2.cab – and they update it every month with each Patch Tuesday.

Windows Update Offline Scan File – wsusscn2.cab

Developers generally use the offline cab file so they can programmatically identify missing updates against a Windows system without access to WSUS, Configuration Manager, or Windows Update.

Microsoft provides two code examples written in VBScript:

Here is a simplified working example of the same using Windows PowerShell:

# Download the wsusscn2.cab file from the Microsoft Update Catalog $Url = 'https://catalog.s.download.windowsupdate.com/microsoftupdate/v6/wsusscan/wsusscn2.cab' $ScanFile = '{0}\wsusscn2.cab' -f $env:temp [System.Net.WebClient]::new().DownloadFile($Url, $ScanFile) # Load the Microsoft.Update.Session COM object $UpdateSession = [Activator]::CreateInstance( [Type]::GetTypeFromProgID("Microsoft.Update.Session") ) $UpdateServiceManager = [Activator]::CreateInstance( [Type]::GetTypeFromProgID("Microsoft.Update.ServiceManager") ) # Add the scan package service $UpdateService = $UpdateServiceManager.AddScanPackageService("Offline Sync Service", $ScanFile) # Create an update searcher $UpdateSearcher = $UpdateSession.CreateUpdateSearcher() $UpdateSearcher.ServerSelection = 3 $UpdateSearcher.ServiceID = $UpdateService.ServiceID.ToString() # Search for missing updates $SearchResult = $UpdateSearcher.Search("IsInstalled=0") # Display the list of missing updates if ($SearchResult.Updates.Count -gt 0) { $SearchResult.Updates } else { Write-Host "No missing updates were found on this system." }

It can take a while for this code to run, especially if you have a slow Internet connection.

While the above is not a lot of code, it is unnecessarily long, especially when compared to how you could otherwise do it using the kbupdate PowerShell module:

$ScanFile = Save-KbScanFile Get-KbNeededUpdate -ScanFilePath $ScanFile
The result of running Get-KbNeededUpdate on Windows 11 to identify missing updates using kbupdate and the Windows offline scan file
kbupdate massively simplifies the process of installing updates using Windows PowerShell. It uses the same WUA API as shown above. It lowers the barrier for adoption and this makes it more accessible for you to patch your Windows devices with PowerShell. The offline scan file can help you in two key scenarios:
  • Identify missing patches in a disconnected environment
  • Provide a reality check on what products or categories you’re not syncing in your WSUS server or Configuration Manager Software Update Point (SUP)

Disconnected Environments

In this context, “disconnected” means endpoints or servers in such an environment do not have easy (or any) access to the Internet. Microsoft offers documentation for configuration WSUS and Configuration Manager for disconnected environments.
Configuration Manager Client Actions
However, for the same reasons previously mentioned, it may be desirable for you to orchestrate your patching by using PowerShell code for creating a bespoke solution. Perhaps you need a way to answer the question of “is this server really patched?” and you need some extra validation. kbupdate is an excellent candidate for use in disconnected environments. Not only can it be used to install updates from a central repository, but it can also leverage the Windows Update offline scan file to identify the missing patches that need installing from the repository. Check out kbupdate’s documentation for an example of Offline patching.

The 100% Compliance Lie

Whether or not in a disconnected environment, WSUS and Configuration Manager – and likely other patching solutions, too – suffer the same fatal flaw: misconfiguration. As a result of such misconfiguration, your reports can indicate you have all the needed updates already deployed and installed, when in fact you don’t. WSUS and Configuration Manager can only tell you what updates you’re missing based on the products or categories you’re syncing into them. Much like I pointed out earlier, Get-KbNeededUpdate will not show any available updates on a Windows 10 or 11 system if you are not syncing the Windows 10/11 product in WSUS, or have any updates approved.
Highlighting the Windows 11 product category in the WSUS console
The same is true for Configuration Manager. In fact, you can be led up the garden path even more with Configuration Manager. Reports for software updates will indicate you are 100% compliant with lovely big green pie charts for this Windows 10 or 11 device if you are not syncing the Windows 10/11 product into your SUP.
Highlighting the Windows 11 product category in the Configuration Manager console
This is an extremely important reason to use the offline scan file, even if it’s to occasionally spot-check your environment. It can provide you with a sanity check and answer the question “is my WSUS/SUP configured correctly?”, “do I have all the patches synced that I need?”, “are my systems really patched?” Answers to these questions can help uncover ghosts in the wires you weren’t previously aware of.

Beyond Operating System Patching

In this post, we discussed how to install the latest version of Windows updates using PowerShell. We focused on how to use the excellent Windows PowerShell module kbupdate, and also what it looks like to interact with the WUA API.

 Remediating devices for missing Windows updates is only a small piece of the enormous battle that is cyber security. While the Operating System is a dominating piece of software on a device, accompanying third-party software is equally important and a significant risk if left unpatched. 

More often than not, it is the most overlooked form of patching. As reported earlier by IBM, outdated third-party software leaves a device vulnerable as an attack vector used by hackers. 

Products like Patch My PC can help you identify and remediate vulnerabilities from outdated third-party software on your devices by automating the packaging and integrating with Microsoft Configuration Manager, Intune, and WSUS.

 Patch My PC offers features to scan your collected installed software inventory for both Configuration Manager and Intune. Coupled with excellent reporting, Patch My PC can help you keep on top of your patching strategy and ensure a better long-term security posture.

Book a live 1-on-1 demo with a Patch My PC Engineer: Live Demo: Free Demo with an Engineer | Patch My PC

Tech Blog

PowerShell Uses - Feature Image

PowerShell Uses – Things to Start Doing, Things to Stop Doing

There are some things in PowerShell that you need to start doing but also stop doing. What is PowerShell and some of the best practices?

Intune Win32 Apps Guide to Availability and Deadlines Feature Image

Intune Win32 apps: A Strategic Guide to Availability and Deadlines

Discover the ins and outs of Intune Management Extension in our latest blog post. We’re exploring its behavior with scheduled win32 app...

Windows Defender Exploit Guard breaks Google Chrome

Often, blog titles are sensationalised and designed to draw the readers attention. In September 2023, we did actually observe the behavior described...
Discovery Apps - Intune Software Inventory - Feature Image

Discovered Apps – The Intune Software Inventory

Is there an Intune Software Inventory? How does Intune detect apps installed in my tenant? Find out everything you need to know about Discovered...

Intune Scope Tags and Role-Based Access Control Explained

In today's interconnected era, it has become increasingly common for large organizations to have multiple IT departments and workers spread across...

Intune Discovered Apps – Missing Inventory Data

At the tail end of June 2023 and into the first week of July 2023, many admins started to report that application inventory data was missing in...
Intune Discovery Apps - Detecting your applications and gaining back control Feature Image

Intune Discovered Apps – Detecting your applications and gaining back control

Learn more about the power of Intune Discovered Apps for application inventory management. Detect and manage your software inventory...

Intune Microsoft Store Integration App Migration Failures (0x87D1041C)

In July 2021, Microsoft announced that both Microsoft Store for Business and Education would be deprecated on March 31, 2023. While Microsoft has...
Automatic Deployment Rules and ConfigMgr

Automatic Deployment Rules (ADR) and ConfigMgr and why you should use them

What is an ADR Getting Started with ADR Creating and Defining an ADR What are Deployment Packages?In this blog we will review Automatic Deployment...

Mastering ConfigMgr Client Actions

In this blog post, we’ll take a deep dive into the various SCCM client actions, including when to use them, what they do, and which log files...

PowerShell Uses – Things to Start Doing, Things to Stop Doing

There are some things in PowerShell that you need to start doing but also stop doing. What is PowerShell and some of the best practices?

Intune Win32 apps: A Strategic Guide to Availability and Deadlines

Discover the ins and outs of Intune Management Extension in our latest blog post. We’re exploring its behavior with scheduled win32 app...

Windows Defender Exploit Guard breaks Google Chrome

Often, blog titles are sensationalised and designed to draw the readers attention. In September 2023, we did actually observe the behavior described...

Discovered Apps – The Intune Software Inventory

Is there an Intune Software Inventory? How does Intune detect apps installed in my tenant? Find out everything you need to know about Discovered...

Intune Scope Tags and Role-Based Access Control Explained

In today's interconnected era, it has become increasingly common for large organizations to have multiple IT departments and workers spread across...

Intune Discovered Apps – Missing Inventory Data

At the tail end of June 2023 and into the first week of July 2023, many admins started to report that application inventory data was missing in...

Intune Discovered Apps – Detecting your applications and gaining back control

Learn more about the power of Intune Discovered Apps for application inventory management. Detect and manage your software inventory...

Intune Microsoft Store Integration App Migration Failures (0x87D1041C)

In July 2021, Microsoft announced that both Microsoft Store for Business and Education would be deprecated on March 31, 2023. While Microsoft has...

Automatic Deployment Rules (ADR) and ConfigMgr and why you should use them

What is an ADR Getting Started with ADR Creating and Defining an ADR What are Deployment Packages?In this blog we will review Automatic Deployment...

Mastering ConfigMgr Client Actions

In this blog post, we’ll take a deep dive into the various SCCM client actions, including when to use them, what they do, and which log files...