Вы можете использовать PowerShell модуль PSWindowsUpdate для управления обновлениями Windows из командной строки. Модуль PSWindowsUpdate не встроен в Windows и доступен для установки из репозитория PowerShell Gallery. PSWindowsUpdate позволяет администраторам удаленно проверять, устанавливать, удалять и скрывать обновления на рабочих станциях и серверах Windows. Модуль PSWindowsUpdate особо ценен при использовании для управления обновлениями в Core редакциях Windows Server (в которых отсутствуют графический интерфейс), а также при настройке образа Windows в режиме аудита.
Содержание:
- Установка модуля управления обновлениями PSWindowsUpdate
- Обзор команд модуля PSWindowsUpdate
- Управление обновлениями Windows на удаленных компьютерах через PowerShell
- Получить список доступных обновлений Windows из PowerShell
- Установка обновлений Windows с помощью Install-WindowsUpdate
- Просмотр истории установленных обновлений Windows (Get-WUHistory)
- Удаление обновлений в Windows с помощью Remove-WindowsUpdate
- Как скрыть ненужные обновления Windows с помощью PowerShell (Hide-WindowsUpdate)?
Установка модуля управления обновлениями PSWindowsUpdate
Если вы используете Windows 10/11 или Windows Server 2022/2019/2016, вы можете установить (обновить) модуль PSWindowsUpdate из онлайн репозитория через менеджер пакетов PackageManagement всего одной командой:
Install-Module -Name PSWindowsUpdate
После окончания установки нужно проверить наличие пакета:
Get-Package -Name PSWindowsUpdate
В старых версиях Windows 2012R2/Windows 8.1 и ниже при установке PowerShell модуля может появится ошибка:
Install-Module: Unable to download from URI.Unable to download the list of available providers. Check your internet connection.
Для установки модуля нужно использовать для подключения протокол TLS 1.2. Включите его:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Если у вас установлена более старая версия Windows (Windows 7/8.1/ Windows Server 2008 R2/ 2012 R2) или отсутствует прямой доступ в Интернет, вы можете установить модуль PSWindowsUpdate вручную (см. полную инструкцию по офлайн установке модулей PowerShell).
- Скачайте модуль PSWindowsUpdate на любой онлайн компьютер:
Save-Module –Name PSWindowsUpdate –Path C:\ps\
; - Скопируйте модуль на целевой компьютер, и поместите его в каталог
%WINDIR%\System32\WindowsPowerShell\v1.0\Modules
(при постоянном использовании модуля это лучший вариант); - Разрешите выполнение PowerShell скриптов:
Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force
- Теперь вы можете импортировать модуль в свою сессию PowerShell:
Import-Module PSWindowsUpdate
Примечание. В Windows 7 / Server 2008 R2 при импорте модуля PSWindowsUpdate вы можете столкнутся с ошибкой вида:
Имя "Unblock-File" не распознано как имя командлета
. Дело в том, что в модуле используются некоторые функции, которые появились только в PowerShell 3.0. Для использования этих функций вам придется обновить PowerShell, либо вручную удалить строку | Unblock-File из файла PSWindowsUpdate.psm1.
После установки модуля PSWindowsUpdate на своем компьютере вы можете удаленно установить его на другие компьютеры или сервера с помощью командлета Update-WUModule. Например, чтобы скопировать PSWindowsUpdate модуль с вашего компьютера на два удаленных сервера, выполните команды (нужен доступ к удаленным серверам по протоколу WinRM):
$Targets = "Server1", "Server2"
Update-WUModule -ComputerName $Targets -local
Чтобы сохранить модуль в сетевой каталог для дальнейшего импорта модуля на других компьютерах, выполните:
Save-Module -Name PSWindowsUpdate –Path \\fs01\ps\
Обзор команд модуля PSWindowsUpdate
Список доступных командлетов модуля можно вывести так:
get-command -module PSWindowsUpdate
Вкратце опишем назначение команд модуля:
- Clear-WUJob – использовать Get-WUJob для вызова задания WUJob в планировщике;
- Download-WindowsUpdate (алиас для Get-WindowsUpdate –Download) — получить список обновлений и скачать их;
- Get-WUInstall, Install-WindowsUpdate (алиас для Get-WindowsUpdate –Install) – установить обвновления;
- Hide-WindowsUpdate (алиас для Get-WindowsUpdate -Hide:$false) – скрыть обновление;
- Uninstall-WindowsUpdate -удалить обновление с помощью Remove-WindowsUpdate;
- Add-WUServiceManager – регистрация сервера обновления (Windows Update Service Manager) на компьютере;
- Enable-WURemoting — включить правила Windows Defender файервола, разрешающие удаленное использование командлета PSWindowsUpdate;
- Get-WindowsUpdate (Get-WUList) — выводит список обновлений, соответствующим указанным критериям, позволяет найти и установить нужное обновление. Это основной командлет модуля PSWindowsUpdate. Позволяет скачать и установить обновления с сервера WSUS или Microsoft Update. Позволяет выбрать категории обновлений, конкретные обновления и указать правила перезагрузки компьютера при установке обновлений;
- Get-WUApiVersion – получить версию агента Windows Update Agent на компьютере;
- Get-WUHistory – вывести список установленных обновлений (история обновлений);
- Get-WUInstallerStatus — проверка состояния службы Windows Installer;
- Get-WUJob – запуска заданий обновления WUJob в Task Scheduler;
- Get-WULastResults — даты последнего поиска и установки обновлений (LastSearchSuccessDate и LastInstallationSuccessDate);
- Get-WURebootStatus — позволяет проверить, нужна ли перезагрузка для применения конкретного обновления;
- Get-WUServiceManager – вывод источников обновлений;
- Get-WUSettings – получить настройки клиента Windows Update;
- Invoke-WUJob – удаленное вызов заданий WUJobs в Task Schduler для немедленного выполнения заданий PSWindowsUpdate.
- Remove-WindowsUpdate – удалить обновление;
- Remove-WUServiceManager – отключить Windows Update Service Manager;
- Set-PSWUSettings – сохранить настройки модуля PSWindowsUpdate в XML файл;
- Set-WUSettings – настройка параметров клиента Windows Update;
- Update-WUModule – обновить модуль PSWindowsUpdate (можно обновить модуль на удаленном компьютере, скопировав его с текущего, или обновить из PSGallery);
- Reset-WUComponents – позволяет сбросить настройка агента Windows Update на компьютере к настройкам по-умолчанию.
Чтобы проверить текущие настройки клиента Windows Update, выполните команду:
Get-WUSettings
ComputerName : WKS22122 WUServer : http://MS-WSUS:8530 WUStatusServer : http://MS-WSUS:8530 AcceptTrustedPublisherCerts : 1 ElevateNonAdmins : 1 DoNotConnectToWindowsUpdateInternetLocations : 1 TargetGroupEnabled : 1 TargetGroup : WorkstationsProd NoAutoUpdate : 0 AUOptions : 3 - Notify before installation ScheduledInstallDay : 0 - Every Day ScheduledInstallTime : 3 UseWUServer : 1 AutoInstallMinorUpdates : 0 AlwaysAutoRebootAtScheduledTime : 0 DetectionFrequencyEnabled : 1 DetectionFrequency : 4
В данном примере клиент Windows Update на компьютере настроен с помощью GPO на получение обновлений с локального сервера WSUS.
Команда
Reset-WUComponents –Verbose
позволяет сбросить все настройки агента Windows Update, перерегистрировать библиотеки и восстановить исходное состояние службы wususerv.
Управление обновлениями Windows на удаленных компьютерах через PowerShell
Практически все командлеты модуля PSWindowsUpdate позволяют управлять установкой обновлений на удаленных компьютерах. Для этого используется атрибут
-Computername Host1, Host2, Host3
. На удаленных компьютерах должен быть включен и настроен WinRM (вручную или через GPO).
Установите модуль PSWindowsUpdate на удаленных компьютерах и разрешите в файерволе доступ по динамическим RPC портам к процессу dllhost.exe. Можно использовать Invoke-Command для настройки модуля PSWindowsUpdate на удаленных компьютерах:
Invoke-Command -ComputerName $computer -ScriptBlock {Set-ExecutionPolicy RemoteSigned -force }
Invoke-Command -ComputerName $computer -ScriptBlock {Import-Module PSWindowsUpdate; Enable-WURemoting}
Модуль PSWindowsUpdate можно использовать для удаленного управлений обновлениями Windows как на компьютерах в домене AD, так и в рабочей группе (потребует определенной настройки PowerShell Remoting)
Для удаленного управления обновлениями компьютерах, нужно добавить имена компьютеров доверенных хостов winrm, или настроить удаленное управление PSRemoting через WinRM HTTPS:
winrm set winrm/config/client ‘@{TrustedHosts="HOST1,HOST2,…"}’
Или с помощью PowerShell:
Set-Item wsman:\localhost\client\TrustedHosts -Value wsk-w10BO1 -Force
Получить список доступных обновлений Windows из PowerShell
Вывести список обновлений, доступных для данного компьютера на сервере обновлений можно с помощью команд Get-WindowsUpdate или Get-WUList.
Чтобы проверить список доступных обновлений на удаленном компьютере, выполните:
Get-WUList –ComputerName server2
Вы можете проверить, откуда должна получать обновления ваша ОС Windows. Выполните команду:
Get-WUServiceManager
ServiceID IsManaged IsDefault Name --------- --------- --------- ---- 8b24b027-1dee-babb-9a95-3517dfb9c552 False False DCat Flighting Prod 855e8a7c-ecb4-4ca3-b045-1dfa50104289 False False Windows Store (DCat Prod) 3da21691-e39d-4da6-8a4b-b43877bcb1b7 True True Windows Server Update Service 9482f4b4-e343-43b6-b170-9a65bc822c77 False False Windows Update
Как вы видите, компьютер настроен на получение обновлений с локального сервера WSUS (Windows Server Update Service = True). В этом случае вы должны увидеть список обновлений, одобренных для вашего компьютера на WSUS.
Если вы хотите просканировать ваш компьютер на серверах Microsoft Update (кроме обновлений Windows на этих серверах содержатся обновления Office и других продуктов) в Интернете, выполните команду:
Get-WUlist -MicrosoftUpdate
Вы получаете предупреждение:
Get-WUlist : Service Windows Update was not found on computer
Чтобы разрешить сканирование на Microsoft Update, выполните команду:
Add-WUServiceManager -ServiceID "7971f918-a847-4430-9279-4a52d1efe18d" -AddServiceFlag 7
Теперь можете выполнить сканирование на Microsoft Update. Как вы видите, в данном случае были найдены дополнительные обновления для Microsoft Visual C++ 2008 и Microsoft Silverlight.
Чтобы проверить версию агента Windows Update на компьютере, выполните команду:
Get-WUApiVersion
ComputerName PSWindowsUpdate PSWUModuleDll ApiVersion WuapiDllVersion ------------ --------------- ------------- ---------- --------------- FS01 2.2.0.2 2.2.0.2 8.0 10.0.19041.1320
Чтобы убрать определенные продукты или конкретные KB из списка обновлений, которые получает ваш компьютер, вы их можете исключить по:
- Категории (-NotCategory);
- Названию (-NotTitle);
- Номеру обновления (-NotKBArticleID).
Например, исключим из списка обновления драйверов, OneDrive и одну конкретную KB:
Get-WUlist -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4533002
Установка обновлений Windows с помощью Install-WindowsUpdate
Чтобы автоматически загрузить и установить все доступные обновления для вашей версии Windows с серверов Windows Update (вместо локального WSUS), выполните:
Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
Ключ AcceptAll включает одобрение установки для всех пакетов, а AutoReboot разрешает автоматическую перезагрузку Windows после установки обновлений.
Также можно использовать следующе параметры:
- IgnoreReboot – запретить автоматическую перезагрузку;
- ScheduleReboot – задать точное время перезагрузки компьютера.
Можете сохранить историю установки обновлений в лог файл (можно использовать вместо WindowsUpdate.log).
Install-WindowsUpdate -AcceptAll -Install -AutoReboot | Out-File "c:\$(get-date -f yyyy-MM-dd)-WindowsUpdate.log" -force
Можно установить только конкретные обновления по номерам KB:
Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install
В данном случае нужно подтверждать установку каждого обновления вручную.
Если вы хотите исключить некоторые обновления из списка на установку, выполните:
Install-WindowsUpdate -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll -IgnoreReboot
Модуль позволяет удаленно запустить установку обновлений сразу на нескольких компьютерах или серверах (на компьютерах должен присутствовать модуль PSWindowsUpdate). Это особенно удобно, так как позволяет администратору не заходить вручную на все сервера во время плановой установки обновлений. Следующая команда установит все доступные обновление на трех удаленных серверах:
ServerNames = “server1, server2, server3”
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate -AcceptAll | Out-File C:\Windows\PSWindowsUpdate.log } -RunNow -Confirm:$false -Verbose -ErrorAction Ignore
Командлет Invoke-WUJob (ранее командлет назывался Invoke-WUInstall) создаст на удаленном компьютере задание планировщика, запускаемое от SYSTEM. Можно указать точное время для установки обновлений Windows:
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate –AcceptAll -AutoReboot | Out-File C:\Windows\PSWindowsUpdate.log } -Confirm:$false -TriggerDate (Get-Date -Hour 20 -Minute 0 -Second 0)
Можно установить обновления на удаленном компьютере и отправить email отчет администратору:
Install-WindowsUpdate -ComputerName server1 -MicrosoftUpdate -AcceptAll - IgnoreReboot -SendReport –PSWUSettings @{SmtpServer="smtp.winitpro.ru";From="[email protected]";To="[email protected]";Port=25} -Verbose
Проверить статус задания установки обновления можно с помощью Get-WUJob:
Get-WUJob -ComputerName $ServerNames
Если команда вернет пустой список, значит задача установки на всех компьютерах выполнена.
Просмотр истории установленных обновлений Windows (Get-WUHistory)
С помощью команды Get-WUHistory вы можете получить список обновлений, установленных на компьютере ранее автоматически или вручную.
Можно получить информацию о дате установки конкретного обновления:
Get-WUHistory| Where-Object {$_.Title -match "KB4517389"} | Select-Object *|ft
Чтобы получить информацию об наличии установленного обновления на нескольких удаленных компьютерах, можно воспользоваться таким кодом:
"server1","server2" | Get-WUHistory| Where-Object {$_.Title -match "KB4011634"} | Select-Object *|ft
Проверить, нужна ли перезагрузка компьютеру после установки обновления:
Get-WURebootStatus –ComputerName WKS80JT
Проверьте значение атрибутов
RebootRequired
и
RebootScheduled
.
Получить дату последней установки обновлений на всех компьютерах в домене можно с помощью командлета Get-ADComputer из модуля AD PowerShell:
$Computers=Get-ADComputer -Filter {enabled -eq "true" -and OperatingSystem -Like '*Windows*' }
Foreach ($Computer in $Computers)
{
Get-WULastResults -ComputerName $Computer.Name|select ComputerName, LastSearchSuccessDate, LastInstallationSuccessDate
}
По аналогии можно найти компьютеры, которые не устаналивали обновления более 40 дней и вывести результат в графическую таблицу Out-GridView:
$result=@()
Foreach ($Computer in $Computers) {
$result+= Get-WULastResults -ComputerName $Computer.Name
}
$result| Where-Object { $_.LastInstallationSuccessDate -lt ((Get-Date).AddDays(-30)) }| Out-GridView
Удаление обновлений в Windows с помощью Remove-WindowsUpdate
Для корректного удаления обновлений используется командлет Remove-WindowsUpdate. Вам достаточно указать номер KB в качестве аргумента параметра KBArticleID. Чтобы отложить автоматическую перезагрузку компьютера можно добавить ключ
–NoRestart
:
Remove-WindowsUpdate -KBArticleID KB4011634 -NoRestart
Как скрыть ненужные обновления Windows с помощью PowerShell (Hide-WindowsUpdate)?
Вы можете скрыть определенные обновления, чтобы они никогда не устанавливались службой обновлений Windows Update на вашем компьютер (чаще всего скрывают обновления драйверов). Например, чтобы скрыть обновления KB2538243 и KB4524570, выполните такие команды:
$HideList = "KB2538243", "KB4524570"
Get-WindowsUpdate -KBArticleID $HideList -Hide
или используйте alias:
Hide-WindowsUpdate -KBArticleID $HideList -Verbose
Теперь при следующем сканировании обновлений с помощью команды
Get-WUlist
скрытые обновления не будут отображаться в списке доступных для установки патчей.
Вывести список обновлений, которые скрыты на данном компьютере можно так:
Get-WindowsUpdate –IsHidden
Обратите внимание, что в колонке Status у скрытых обновлений появился атрибут H (Hidden).
Отменить скрытие некоторых обновлений можно так:
Get-WindowsUpdate -KBArticleID $HideList -WithHidden -Hide:$false
или так:
Show-WindowsUpdate -KBArticleID $HideList
Для тех, кто себя некомфортно чувствует в консоли PowerShell, для управления обновлениями Windows 10 могу порекомендовать графическую утилиту Windows Update MiniTool.
You can use PowerShell to install Windows Updates automatically, unattended and simple. Neat, right? For this, you don’t have to have an enterprise environment with WSUS, or Windows Server, but since this is Sysadmins of the North, I assume you do. In this post I’m going to show you how to install Windows Updates with PowerShell and the PSWindowsUpdate module.
Some code might show pseudo-code. Most is copied from my older Dutch post “Installeer Windows updates via PowerShell” on ITFAQ.nl.
To being able to install Windows Updates with PowerShell, you need Powershell installed. Either 5.1 or 7.3, at the time of this writing. If you fulfill this requirement, you can install and use PSWindowsUpdate module. Windows Updates are easily installed from either Windows Update or Windows Server Update Services (WSUS).
Install PSWindowsUpdate module
PSWindowsUpdate is a PowerShell module to install Windows Updates. There are more modules for this purpose, but this is the one I use and am used to. To make this module available, start a PowerShell instance as administrator.
Choose “Run as Administrator”.
If necessary, you first have to set the execution policy to RemoteSigned: Set-ExecutionPolicy RemoteSigned
. After this you can install the module:
- If required:
Install-PackageProvider -Name NuGet -Force
(works only with PowerShell 5.1, not 7) Install-Module -Name PSWindowsUpdate -Force
When this command is successfully run (there is no confirmation), you can use Get-Command
to list available cmdlets and aliases. Provide Get-Command
with the -Module
argument and module name:
Get-Command -Module PSWindowsUpdate
Get-Command -Module PSWindowsUpdate
CommandType Name Version Source
----------- ---- ------- ------
Alias Clear-WUJob 2.2.0.3 PSWindowsUpdate
Alias Download-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Alias Get-WUInstall 2.2.0.3 PSWindowsUpdate
Alias Get-WUList 2.2.0.3 PSWindowsUpdate
Alias Hide-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Alias Install-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Alias Show-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Alias UnHide-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Alias Uninstall-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Cmdlet Add-WUServiceManager 2.2.0.3 PSWindowsUpdate
Cmdlet Enable-WURemoting 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUApiVersion 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUHistory 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUInstallerStatus 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUJob 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WULastResults 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUOfflineMSU 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WURebootStatus 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUServiceManager 2.2.0.3 PSWindowsUpdate
Cmdlet Get-WUSettings 2.2.0.3 PSWindowsUpdate
Cmdlet Invoke-WUJob 2.2.0.3 PSWindowsUpdate
Cmdlet Remove-WindowsUpdate 2.2.0.3 PSWindowsUpdate
Cmdlet Remove-WUServiceManager 2.2.0.3 PSWindowsUpdate
Cmdlet Reset-WUComponents 2.2.0.3 PSWindowsUpdate
Cmdlet Set-PSWUSettings 2.2.0.3 PSWindowsUpdate
Cmdlet Set-WUSettings 2.2.0.3 PSWindowsUpdate
Cmdlet Update-WUModule 2.2.0.3 PSWindowsUpdate
Searching for available Windows Updates
Now you have PSWindowsUpdate installed and available, you want to search WSUS or Windows Update for available updates, right? Here’s how to search for available updates:
Get-WindowsUpdate
ComputerName Status KB Size Title
------------ ------ -- ---- -----
LAPTOPJANR ------- KB2267602 821MB Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Ve…
Scan for, or detect, new updates with Microsoft.Update.AutoUpdate
COM-object in PowerShell:(new-object -Comobject Microsoft.Update.AutoUpdate).detectnow()
Download and install found updates
After finding updates to install, you need to install them. That’s as easy as:
- Download & Install (choose accept when requested):
Install-WindowsUpdate -KBArticleID KB2267602 -ForceDownload
This accepts, downloads and installs the update. When in doubt, you can always execute the command with -ForceInstall
later:
Install-WindowsUpdate -KBArticleID KB2267602 -ForceInstall
You can do a lot more with PSWindowsUpdate module for PowerShell. For example, you can plan and schedule the downloading and installing of updates, which may be perfect in our update routine. Install Windows Updates silently See Get-Help Install-WindowsUpdate
for more information and examples. If you are in a WSUS environment and want to search WindowsUpdate, use -WindowsUpdate
command argument.
Schedule Windows Updates download and installation silently with PowerShell and PSWindowsUpdate
As said, you can use PSWindowsUpdate to schedule the download and installation of Windows Update, to make the process silent. Perfect! Schedule updates for automatic installation, here is an example:
Invoke-WUJob -Script {
Import-Alias PSWindowsUpdate; Install-WindowsUpdate -IgnoreUserInput -Verbose -AcceptAll -IgnoreReboot | Out-File ~\log\PSWindowsUpdate-$(Get-Date -format "yyyyMMdd").log
} -Confirm:$false -Verbose -TriggerDate (Get-Date -Day 15 -Hour 12 -Minute 00 -Second 0)
On a local computer, this creates an scheduled task with name “PSWindowsUpdate” to run on day 15, hour 12, minute 00 and second 0. A log is saved in ~\log with name PSWindowsUpdate-$(Get-Date -format "yyyyMMdd").log
.
If you want to schedule Windows Updates on remote computers, use the -ComputerName
parameter:
Invoke-WUJob -ComputerName SRV01,SRV02,SRV03 -Script {
Import-Alias PSWindowsUpdate; Install-WindowsUpdate -IgnoreUserInput -Verbose -AcceptAll -IgnoreReboot | Out-File ~\log\PSWindowsUpdate-$(Get-Date -format "yyyyMMdd").log
} -Confirm:$false -Verbose -TriggerDate (Get-Date -Day 15 -Hour 12 -Minute 00 -Second 0)
This goes perfectly with Get-ADComputer in your Active Directory Domain.
Check for Pending Reboot after Windows Update with PowerShell (Bonus)
Need to check for a pending reboot after installing Windows Updates? Use the Windows Registry:
if((Get-Item "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction SilentlyContinue).Property) {
write-output "reboot pending"
}
Instead of using Write-OutPut
you can also perform a reboot action here: Restart-Computer -Force
.
Conclusion installing Windows Updates using PSWindowsUpdate module in PowerShell
In this post I showed you how you can use PowerShell to install Windows Updates. Quickly and silently. This makes the use of PSWindowsUpdate module perfect for your day to day automation. The module even supports scheduling (on remote computers too!), it has the ability to search WSUS and Windows Update for updates, scheduling and performing the download and installation of updates, and it’s still being actively developed.
Installing Windows Updates manually can be a drag. Why not automate the entire process with PowerShell? Get started controlling Windows updates with the PSWindowsUpdate module in PowerShell!
In this tutorial, you will learn how to download and install updates on your Windows machine through PowerShell.
A FREE read only tool that scans your AD and generates multiple interactive reports for you to measure the effectiveness of your password policies against a brute-force attack. Download Specops Password Auditor now!
Prerequisites
This tutorial uses Windows 10 Build 19042 for demonstrations throughout this tutorial, but older ones, such as Windows 7 and 8.1, will work.
Installing the PSWindowsUpdate Module
The PSWindowsUpdate module is a third-party module available in PowerShell Gallery that lets you manage Windows updates from the PowerShell console. The PowerShell Gallery is the central repository where you can find and share PowerShell modules.
With the PSWindowsUpdate module, you can remotely check, install, update and remove updates on Windows servers and workstations. But first, you need to install the PSWindowsUpdate module on your machine.
1. Open PowerShell as administrator.
2. Run the Install-Module
command to download and install the PSWindowUpdate
module from the PowerShell gallery repository. The -Force
parameter tells the command to ignore prompt messages and continue installing the module.
Install-Module -Name PSWindowsUpdate -Force
If you’re on an older version of Windows, you can download the PSWindowsUpdate module manually.
3. Next, run the Import-Module
command below to import the PSWindowsUpdate
module to PowerShell’s current session. Once imported, you can then use the module to manage Windows updates on your machine.
You may run into an error importing the module for the first time saying “The specified module ‘PSWindowsUpdate’ was not loaded”. In that case, you must allow executing scripts on your machine.
Run the command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
to enable execute remote scripts on your computer. Now try importing thePSWindowsUpdate
module again.
Import-Module PSWindowsUpdate
4. Finally, run the command below to see all commands (Get-Command
) available for the PSWindowsUpdate
module. Some of these commands are what you will use to manage Windows updates on your machine. Get-Command -Module PSWindowsUpdate
Get-Command -Module PSWindowsUpdate
Checking for Available Windows Updates
With the PSWindowsUpdate module installed, you can now run a command to list the updates available for your computer before installing them. Checking the list of updates is a good practice to avoid installing an update you don’t need.
Run the Get-WindowsUpdate
command to list all the Windows updates
Below, you can see the list of available Windows updates along with their Knowledge-Base (KB) numbers. Take note of any KB number of a Windows update that you may want to prevent installing later, perhaps one that you deem not important.
Perhaps you also want to check where Windows gets an update from to see if the source is trustworthy. If so, the Get-WUServiceManager
command will do the trick.
Run the Get-WUServiceManager
to show the list of available update services.
There’s no official documentation about the update the sources, but each is defined below:
- Microsoft Update – the standard update source
- DCat Flighting Prod – an alternative MS supdate ource for specific flighted update items (from previews, etc)
- Windows Store (DCat Prod) – normally just Windows Store, but has Dcat Prod when for insider preview PC
- Windows Update – an older update source for Windows Vista and older Windows OS.
Excluding Windows Updates from Installing
Now you’ve seen the Windows updates available, perhaps you prefer not to install some of them on your computer. In that case, you can choose not to install them by hiding them.
Run the Hide-WindowsUpdate
command below to hide a Windows update tagged with the specified KB number (-KBArticleID KB4052623
). You can specify the KB number you took note of in the “Checking for Available Windows Updates” section instead.
PowerShell will ask for your confirmation before executing the command. Confirm the command with the “A” key, then press Enter.
Hide-WindowsUpdate -KBArticleID KB4052623
If you change your mind and want to install the update in the future, you can show the update similar to how you hid the update. To show the update, run the
Show-WindowsUpdate
command along with the update’s KB number, like this:Show-WindowsUpdate -KBArticleID KB4052623
Installing Windows Updates
Now that you can discover and exclude some updates from installing, let’s now check out how to install them.
But before installing updates, checking if updates require a system reboot is a good practice. Why? Knowing whether the Windows updates require a reboot beforehand tells you to save all your work and complete other ongoing installations before diving to the Windows update.
Now run the Get-WURebootStatus
command to determine if any of the Windows updates require a reboot. The command returns either True
or False
value to indicate the reboot status
Below, you can see the command returned a False value, which indicates a reboot is not required. So go nuts and install the updates you deem are necessary.
Downloading and Installing All Available Updates
If you’re not picky when it comes to updates, running the Install-WindowsUpdate
command on its own lets you install all available Windows updates. But perhaps, you want to install the updates without having to accept prompts. If so, you need to add the -AcceptAll
parameter as shown below.
Run the Install-WindowsUpdate
command below to install all available Windows updates. The -AcceptAll
parameter tells the command to suppress prompts and continue installing all updates.
If you prefer to reboot your computer once the installation is completed automatically, add the -AutoReboot
parameter.
Install-WindowsUpdate -AcceptAll -AutoReboot
If you prefer to install selected updates only, add the
-KBArticleID
parameter in theInstall-WindowsUpdate
command, followed by the update’s KB number, like this:Install-WindowsUpdate -KBArticleID KB2267602
Checking Windows Update History
Now you have installed windows updates on your computer, but perhaps something has gone wrong during the installation. If so, you can check your update history using the Get-WUHistory
command. The Get-WUHistory
prints out all the installed updates to the console with their installation result.
Run the Get-WUHistory
command below to check Windows update history.
Below, you can see that most of the updates have the Succeeded result status, while some have InProgress status.
Uninstalling Windows Updates
There are times when you install an update you don’t deem important at the moment, or there are updates you suspect of causing an issue on your system. In those times, you can properly uninstall the updates with the Remove-WindowsUpdate
command.
Run the Remove-WindowsUpdate
command below to uninstall a Windows update tagged with a specific KB number (-KBArticleID KB2267602
).
PowerShell will require confirmation before executing the command. Press the “A” key and hit enter to confirm the command.
Remove-WindowsUpdate -KBArticleID KB2267602
Enforce compliance requirements, block over 3 billion compromised passwords, and help users create stronger passwords in Active Directory with dynamic end-user feedback. Contact us today about Specops Password Policy!
Conclusion
Throughout this tutorial, you’ve learned about the PSWindowsUpdate Module. You’ve also gone through selectively installing and uninstalling Windows updates.
You’ve learned that you have full control over the Windows updates with PowerShell. Now, would you prefer installing updates in PowerShell over a GUI method? Perhaps learn more about building a Windows update report?
Last updated on May 6, 2022
As is well known, keeping systems updated is essential to protecting enterprises from malicious attacks and security breaches that may compromise confidential information or even cause sensitive data losses.
Installing Windows update patches has always been a tedious, complex, and long process. Although Microsoft eases these procedures through tools such as Windows Server Update Services (WSUS) or System Center Configuration Manager (SCCM), administrators still require command-line tools to automate the installation of the update in certain scenarios. The PowerShell Windows Update module, or PSWindowsUpdate, is one such tool.
How to install PSWindowsUpdate
PSWindowsUpdate is a third-party module that is not integrated into Windows by default. It can be downloaded from the PowerShell gallery, the most used repository for sharing PowerShell code. This module includes different cmdlets to manage the deployment of Windows updates from the command line.
- Download the latest PSWindowsUpdate version from the PowerShell gallery.
**Previous versions of the module are also available in the Microsoft Technet Gallery, but Microsoft has retired this repository and now remains in read-only mode.
- Create a new folder named “PSWindowsUpdate” in %WINDIR%\System32\WindowsPowerShell\v1.0\Modules and extract the content of the nupkg file.
**A NuGet package is a ZIP archive with some extra files. Some browsers, like Internet Explorer, automatically replace the .nupkg file extension with .zip
- Open an elevated PowerShell prompt and run Set-ExecutionPolicy RemoteSigned to allow the execution of scripts signed by a trusted publisher.
- Install Import-Module -Name PSWindowsUpdate.
If the PowerShell setup is already configured to allow online downloads, the PSWindowsUpdate module can also be installed directly from the online repository (PSGallery) running Install-Module -Name PSWindowsUpdate.
Commands in PSWindowsUpdate
Installed aliases and cmdlets can be displayed by typing Get-Command–module PSWindowsUpdate.
A brief description of principal commands is described below:
Get-WindowsUpdate: This is the main cmdlet of the module. It lists, downloads, installs, or hides a list of updates meeting predefined requisites and sets the rules of the restarts when installing the updates.
Remove-WindowsUpdate: Uninstalls an update.
Add-WUServiceManage: Registers a new Windows Update API Service Manager.
Get-WUHistory: Shows a list of installed updates.
Get-WUSettings: Gets Windows Update client settings.
Get-WUInstallerStatus: Gets Windows Update Installer Status, whether it is busy or not.
Enable-WURemoting: Enables firewall rules for PSWindowsUpdate remoting.
Invoke-WUJob: Invokes PSWindowsUpdate actions remotely.
Clear-WUJob: Clears the WUJob in Task Scheduler.
Get-WUInstall, Install-WindowsUpdate (alias for Get-WindowsUpdate –Install): Installs Windows updates.
Uninstall-WindowsUpdate: Removes updates using the Remove-WindowsUpdate command.
Get-WULastResults: Gets the dates for the last search and installation of updates.
Get-WURebootStatus: Checks if a reboot is needed to apply an update.
Remove-WUServiceManager: Disables the Windows Update Service Manager.
Set-PSWUSettings: Saves settings of the PSWindowsUpdate module to an XML file.
Set-WUSettings: Configures the Windows Update client’s settings.
Reset-WUComponents: Resets the Windows Update agent to its default state.
Like for all PowerShell cmdlets, different usage examples can be shown for each command by typing Get-Help “command” -examples.
PSWindowsUpdate Main Parameters
The previous section shows that the PSWindowsUpdate module includes different predefined aliases to ease patching processes. However, the main parameters for the Get-WindowsUpdate cmdlet will be listed and explained below:
Filtering Updates:
- AcceptAll: Downloads or installs all available updates.
- KBArticleID: Finds updates that contain a KBArticleID (or sets of KBArticleIDs).
- UpdateID: Specifies updates with a specific UUID (or sets of UUIDs).
- Category: Specifies updates that contain a specified category name, such as ‘Updates,’ ‘Security Updates’ or ‘Critical Updates’.
- Title: Finds updates that match part of title.
- Severity: Finds updates that match part of severity, such as ‘Important,’ ‘Critical’ or ‘Moderate’.
- UpdateType: Finds updates with a specific type, such as ‘Driver’ and ‘Software.’ Default value contains all updates.
Actions and Targets:
- Download: downloads approved updates but does not install them.
- Install: installs approved updates.
- Hide: hides specified updates to prevent them to being installed.
- ScheduleJob: specifies date when job will start.
- SendReport: sends a report from the installation process.
- ComputerName: specifies target server or computer.
Client Restart Behavior:
- AutoReboot: automatically reboots system if required.
- IgnoreReboot: suppresses automatic restarts.
- ScheduleReboot: specifies the date when the system will be rebooted.
How to Avoid Accidental Installs
Windows updates and patches improve the features and stability of the system. However, some updates can mess up your system and cause instability, especially automatic updates for legacy software such as graphic card drivers. To avoid automatic updates and accidental installs for such applications, you can pause Windows updates.
Alternatively, you can hide the specific updates for those features you don’t want to get updated. When you hide the updates, Windows can no longer download and install such updates. Before you can hide the update, you need to find out its details, including its knowledge base (KB) number and title. Type the cmdlet below to list all the available updates on your system:
Get-WUList
To hide a specific update using the KB number, use your mouse to copy that KB number. Next, type the command below:
Hide-WUUpdate -KBArticleID KB_Number
Highlight the “KB_Number” and click paste to replace that part with the actual KB number.
When prompted to confirm the action, type A, and hit the Enter key. If the command succeeds, the “Get-WUList” lists all the available updates, with hidden updates appearing with the symbol “H” under their status.
The KB number for the update may not be available for some updates. In this case, you can use the title to hide the update. To do this, list all the available updates via the cmdlet below:
Get-WUList
Next, use your mouse to copy the update title. Ensure it is distinct from other update titles. Now, type below command below to hide the update:
Hide-WUUpdate -Title “Update_Title”
Don’t forget to paste the actual update title in the “Update Title” section.
When prompted to confirm the action, type A, and hit the Enter key. If the command succeeds, the “Get-WUList” lists all the available updates. However, the status of hidden updates appears with the symbol “H” underneath them.
How to Determine Errors
It is of crucial importance to have as much information as possible about Windows Updates installation processes in order to be able to fix erroneous deployments. The Get-WindowsUpdate cmdlet and the rest of the cmdlets available in the module provide a very detailed log level when managing updates, including status, KB ID, Size, or Title.
Centralizing all of the computer logs and analyzing them to search for errors, administrators will always be able to know the patch level of their Windows computers and servers.
Check and Download Windows Updates with PowerShell
You can use PowerShell to check and download Windows updates from a server set up with Windows Server Update Services (WSUS).
To check where a computer gets its updates from, run the Get-WUServiceManager command. If you see a Windows Server Update Service = True in the results, that means that it is set to receive updates from your WSUS server.
To get a list of updates for a remote server or computer, run Get-WUList –Computername computername. For example, Get-WUList –ComputerName server1.
If you need updates for Microsoft Office and other Microsoft products, you can also scan for updates from Microsoft Update servers by running Get-WUList –MicrosoftUpdate. If you get a warning, run Add-WUServiceManager -ServiceID “7971f918-a847-4430-9279-4a52d1efe18d” -AddServiceFlag 7, then run the command again.
To install all updates without getting approval prompts for each package, run Install-WindowsUpdate –AcceptAll. To ignore reboots at the end without a prompt, add an –IgnoreReboot switch at the end, e.g., Install-WindowsUpdate –AcceptAll –IgnoreReboot.
Install Windows Updates on Remote Computers with PowerShell
You can use PowerShell to install updates to multiple remote servers simultaneously, so long as PSWindowsUpdate is also installed on the servers. To install Windows Updates on two remote servers, for example, you need to run:
Invoke-WUInstall -ComputerName server1, server2-Script {ipmo PSWindowsUpdate; Get-WUInstall -AcceptAll -AutoReboot | Out-File C:\Windows\PSWindowsUpdate.log } -Confirm:$false -Verbose -SkipModuleTest –RunNow
Flexible PowerShell management with Parallels RAS
Parallels® Remote Application Server (RAS) is a remote work solution that provides 24/7 virtual access to applications and desktops from any device.
Many administrators decide to build their Parallels RAS farms based on templates to optimize the new machine’s deployment time and management efforts. When working with templates and cloning techniques, patching procedures are only done once in the master image. Deploying new machines based on the updated template will upgrade the environment within minutes.
Parallels RAS PowerShell SDK (Software Development Kit) includes a complete set of tools to manage and configure RAS farms, including specific cmdlets to create templates from existing virtual machines or deploy new machines based on those templates. By combining these commands with the PSWindowsUpdate PowerShell module, administrators will be able to automate the complete patching process of their infrastructure servers and their template-based machines.
Different RAS cmdlets can be used to automate the updates installation processes, as seen in this example: Parallels RAS PowerShell – VDI Example.
The complete set of RAS commands is available here: Parallels RAS PowerShell Reference.
See how Parallels RAS can simplify the Windows Updates management process!
Download the Trial
You can use the PSWindowsUpdate PowerShell module to manage Windows updates from the command line. The PSWindowsUpdate module is not built into Windows and is available for installation from the PowerShell Gallery repository. PSWindowsUpdate allows administrators to remotely check, install, remove, and hide updates on Windows servers and workstations. The PSWindowsUpdate module is especially valuable to manage updates on Windows Server Core or Hyper-V Server (which don’t have a GUI), and when configuring a Windows image in the audit mode.
Contents:
- Installing the PSWindowsUpdate Module
- PSWindowsUpdate Cmdlets List
- Scan and Download Windows Updates with PowerShell
- Installing Windows Updates with PowerShell (Install-WindowsUpdate)
- Install Windows Update on Remote Computers with PowerShell
- Check Windows Update History with PowerShell (Get-WUHistory)
- Uninstalling Windows Updates with PowerShell (Remove-WindowsUpdate)
- How to Hide Windows Updates with PowerShell?
Installing the PSWindowsUpdate Module
You can install the PSWindowsUpdate module on Windows 10/11 and Windows Server 2022/2019/2016 from the online repository (PSGallery) using the command:
Install-Module -Name PSWindowsUpdate -Force
After the installation is complete, you need to check the package:
Get-Package -Name PSWindowsUpdate
When installing the PowerShell module on earlier versions of Windows 2012R2/Windows 8.1 and below, you may receive an error:
Install-Module: Unable to download from URI.Unable to download the list of available providers. Check your internet connection.
To install the module, you need to use the TLS 1.2 protocol for connection. Enable it for the current PowerShell session with the command:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
https://woshub.com/powershell-install-module-unable-download-uri/
If you have an older Windows version (Windows 7/8.1/Windows Server 2008 R2/2012 R2) or you don’t have direct Internet access, you can install PSWindowsUpdate manually (check the guide “How to install PowerShell modules offline?”).
- Download the PSWindowsUpdate module to any online computer:
Save-Module –Name PSWindowsUpdate –Path C:\ps\
; - Copy the module to the following folder on the target computer
%WINDIR%\System32\WindowsPowerShell\v1.0\Modules
; - Configure the PowerShell script execution policy:
Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force
- You can now import the module into your PowerShell session:
Import-Module PSWindowsUpdate
Note. In Windows 7/Windows Server 2008 R2, when importing the PSWindowsUpdate module, the following error may appear: The term “Unblock-File” is not recognized as the name of a cmdlet. The cause is that the module uses some functions that appeared only in PowerShell 3.0. To use these functions, you will have either to update the PowerShell version or delete the | Unblock-File
line from the PSWindowsUpdate.psm1 file manually.
After installing the PSWindowsUpdate module on your computer, you can remotely install it on other computers or servers using the Update-WUModule cmdlet. For example, to copy the PSWindowsUpdate module from your computer to two remote hosts, run the commands (you need access to the remote servers via the WinRM protocol):
$Targets = "lon-fs02", "lon-db01"
Update-WUModule -ComputerName $Targets –Local
To save (export) the PoSh module to a shared network folder for further importing on other computers, run:
Save-Module -Name PSWindowsUpdate –Path \\lon-fs02\psmodules\
PSWindowsUpdate Cmdlets List
You can display the list of available cmdlets in the PSWindowsUpdate module as follows:
get-command -module PSWindowsUpdate
Let’s describe the usage of the module commands in brief:
- Clear-WUJob – use the Get-WUJob to clear the WUJob in Task Scheduler;
- Download-WindowsUpdate (alias for
Get-WindowsUpdate –Download
) — get a list of updates and download them; - Get-WUInstall, Install-WindowsUpdate (alias for
Get-WindowsUpdate –Install
) – install Windows updates; - Hide-WindowsUpdate (alias for
Get-WindowsUpdate -Hide:$false
) – hide update; - Uninstall-WindowsUpdate – remove update using the Remove-WindowsUpdate;
- Add-WUServiceManager – register the update server (Windows Update Service Manager) on the computer;
- Enable-WURemoting — enable Windows Defender firewall rules to allow remote use of the PSWindowsUpdate cmdlets;
- Get-WindowsUpdate (Get-WUList) — displays a list of updates that match the specified criteria, allows you to find and install the updates. This is the main cmdlet of the PSWindowsUpdate module. Allows to download and install updates from a WSUS server or Microsoft Update. Allows you to select update categories, specific updates and set the rules of a computer restart when installing the updates;
- Get-WUApiVersion – get the Windows Update Agent version on the computer;
- Get-WUHistory – display a list of installed updates (update history);
- Get-WUInstallerStatus — check the Windows Installer service status;
- Get-WUJob – check for WUJob update tasks in the Task Scheduler;
- Get-WULastResults — dates of the last search and installation of updates (LastSearchSuccessDate and LastInstallationSuccessDate);
- Get-WURebootStatus — allows you to check whether a reboot is needed to apply a specific update;
- Get-WUServiceManager – list update sources;
- Get-WUSettings – get Windows Update client settings;
- Invoke-WUJob – remotely call WUJobs task in the Task Scheduler to immediately execute PSWindowsUpdate commands;
- Remove-WindowsUpdate – allows to uninstall an update by KB ID;
- Remove-WUServiceManager – disable Windows Update Service Manager;
- Set-PSWUSettings – save PSWindowsUpdate module settings to the XML file;
- Set-WUSettings – configure Windows Update client settings;
- Update-WUModule – update the PSWindowsUpdate module (you can update the module on a remote computer by copying it from the current one, or updating from PSGallery);
- Reset-WUComponents – allows you to reset the Windows Update agent on the computer to the default state.
To check the current Windows Update client settings, run the command:
Get-WUSettings
ComputerName : WKS5S2N39S2 WUServer : http://MN-WSUS:8530 WUStatusServer : http://MN-WSUS:8530 AcceptTrustedPublisherCerts : 1 ElevateNonAdmins : 1 DoNotConnectToWindowsUpdateInternetLocations : 1 TargetGroupEnabled : 1 TargetGroup : ServersProd NoAutoUpdate : 0 AUOptions : 3 - Notify before installation ScheduledInstallDay : 0 - Every Day ScheduledInstallTime : 3 UseWUServer : 1 AutoInstallMinorUpdates : 0 AlwaysAutoRebootAtScheduledTime : 0 DetectionFrequencyEnabled : 1 DetectionFrequency : 4
In this example, the Windows Update agent on the computer is configured with a GPO to receive updates from the local WSUS server.
The Reset-WUComponents -Verbose
cmdlet allows you to reset all Windows Update Agent settings, re-register libraries, and restore the wususerv
service to its default state.
Scan and Download Windows Updates with PowerShell
You can list the updates available for the current computer on the update server using the Get-WindowsUpdate
or Get-WUList
commands.
To check the list of available updates on a remote computer, run this command:
Get-WUList –ComputerName server2
You can check where your Windows should receive updates from. Run the following command:
Get-WUServiceManager
ServiceID IsManaged IsDefault Name --------- --------- --------- ---- 8b24b027-1dee-babb-9a95-3517dfb9c552 False False DCat Flighting Prod 855e8a7c-ecb4-4ca3-b045-1dfa50104289 False False Windows Store (DCat Prod) 3da21691-e39d-4da6-8a4b-b43877bcb1b7 True True Windows Server Update Service 9482f4b4-e343-43b6-b170-9a65bc822c77 False False Windows Update
As you can see, the computer is configured to receive updates from the local WSUS server (Windows Server Update Service = True). In this case, you should see a list of updates approved for your computer.
If you want to scan your computer against Microsoft Update servers on the Internet (in addition to Windows updates, these servers contain Office and other Microsoft product updates), run this command:
Get-WUlist -MicrosoftUpdate
You will get this warning:
Get-WUlist : Service Windows Update was not found on computer. Use Get-WUServiceManager to get registered service.
To allow scanning on Microsoft Update, run this command:
Add-WUServiceManager -ServiceID "7971f918-a847-4430-9279-4a52d1efe18d" -AddServiceFlag 7
You can now scan against Microsoft Update. In this case, additional updates were found for Microsoft Visual C ++ 2008 and Microsoft Silverlight.
To check the version of the Windows Update Agent on the computer, run the command:
Get-WUApiVersion
ComputerName PSWindowsUpdate PSWUModuleDll ApiVersion WuapiDllVersion ------------ --------------- ------------- ---------- --------------- DESKTOP-J... 2.1.1.2 2.2.0.2 8.0 10.0.19041.1320
To remove specific products or KBs from the list of updates received by your computer, you can exclude them by:
- Category (
-NotCategory
); - Title (
-NotCategory
); - Update number (
-NotKBArticleID
).
For example, let’s exclude OneDrive, driver updates, and the specific KB from the list:
Get-WUlist -NotCategory "Drivers" -NotTitle "OneDrive" -NotKBArticleID KB4489873
Installing Windows Updates with PowerShell (Install-WindowsUpdate)
To automatically download and install all available updates for your Windows device from Windows Update servers (instead of local WSUS), run the command:
Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
The AcceptAll parameter accepts the installation of all update packages, and AutoReboot allows Windows to automatically restart after the updates are installed.
You can also use the following options:
- IgnoreReboot – disable automatic reboot;
- ScheduleReboot – set the exact time to restart the computer.
You can save the update installation history to a log file (you can use it instead of WindowsUpdate.log file).
Install-WindowsUpdate -AcceptAll -Install -AutoReboot | Out-File "c:\logs\$(get-date -f yyyy-MM-dd)-WindowsUpdate.log" -force
You can install only the specific update packages by KB numbers:
Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install
In this case, you need to confirm the installation of each update manually.
If you want to exclude certain updates from the installation list, run this command:
Install-WindowsUpdate -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll -IgnoreReboot
Install Windows Update on Remote Computers with PowerShell
The PSWindowsUpdate module allows you to install updates remotely on multiple workstations or servers at once (the PSWindowsUpdate must be installed/imported on these computers). This is very convenient because the administrator doesn’t have to manually log on to remote Windows hosts to install updates. WinRM must be enabled and configured on remote computers (manually or via GPO).
Almost all PSWindowsUpdate module cmdlets allow you to manage and install Windows updates on remote computers with the –Computername
attribute.
Install the PSWindowsUpdate module on remote computers and allow access via dynamic RPC ports to the dllhost.exe process in the Windows Defender Firewall. You can use the Invoke-Command cmdlet to configure the PSWindowsUpdate module on remote computers:
$Targets = "lon-fs02", "lon-db01"
Invoke-Command -ComputerName $Target -ScriptBlock {Set-ExecutionPolicy RemoteSigned -force }
Invoke-Command -ComputerName $Target -ScriptBlock {Import-Module PSWindowsUpdate; Enable-WURemoting}
The PSWindowsUpdate module can be used to remotely manage Windows updates both on computers in an AD domain and in a workgroup (requires PowerShell Remoting configuration for workgroup environment).
In order to manage updates on remote computers, you need to add hostnames to your winrm trusted host list or configure PowerShell Remoting (WinRM) via HTTPS:
winrm set winrm/config/client '@{TrustedHosts="server1,server2,…"}'
Or with PowerShell :
Set-Item wsman:\localhost\client\TrustedHosts -Value server1 -Force
The following command will install all available updates on three remote Windows hosts:
$ServerNames = "server1, server2, server3"
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate -AcceptAll | Out-File C:\Windows\PSWindowsUpdate.log } -RunNow -Confirm:$false -Verbose -ErrorAction Ignore
The Invoke-WUJob cmdlet (previously called Invoke-WUInstall) will create a scheduler task on the remote computer that runs under a local SYSTEM account.
You can specify the exact time to install Windows updates:
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate –AcceptAll -AutoReboot | Out-File C:\Windows\PSWindowsUpdate.log } -Confirm:$false -TriggerDate (Get-Date -Hour 22 -Minute 0 -Second 0)
You can check the status of the update installation task using the Get-WUJob:
Get-WUJob -ComputerName $ServerNames
If the command returns an empty list, then the update installation task on all computers has been completed.
You can install updates on a remote computer and send an email report to the administrator:
Install-WindowsUpdate -ComputerName nysrv1 -MicrosoftUpdate -AcceptAll - IgnoreReboot -SendReport –PSWUSettings @{SmtpServer="smtp.woshub.com";From="updat[email protected]";To="[email protected]";Port=25} -Verbose
Check Windows Update History with PowerShell (Get-WUHistory)
Using the Get-WUHistory cmdlet, you can get the list of updates installed on a computer earlier automatically or manually.
You can get the information about the installation date of a specific update:
Get-WUHistory| Where-Object {$_.Title -match "KB4517389"} | Select-Object *|ft
To find out if the specific update has been installed on multiple remote computers, you can use this PowerShell code:
"server1","server2" | Get-WUHistory| Where-Object {$_.Title -match "KB4011634"} | Select-Object *|ft
Check if the computer needs to be restarted after installing the update (pending reboot):
Get-WURebootStatus –ComputerName WKS21TJS
Check the value of the RebootRequired and RebootScheduled attributes.
You can generate a report with the dates when updates were last installed on all computers in the domain using the Get-ADComputer cmdlet (from the Active Directory for PowerShell module):
$Computers=Get-ADComputer -Filter {enabled -eq "true" -and OperatingSystem -Like '*Windows*' }
Foreach ($Computer in $Computers)
{
Get-WULastResults -ComputerName $Computer.Name|select ComputerName, LastSearchSuccessDate, LastInstallationSuccessDate
}
By analogy, you can find computers that have not installed updates for more than 60 days and display the result in the Out-GridView interactive table:
$result=@()
Foreach ($Computer in $Computers) {
$result+= Get-WULastResults -ComputerName $Computer.Name
}
$result| Where-Object { $_.LastInstallationSuccessDate -lt ((Get-Date).AddDays(-60)) }| Out-GridView
Uninstalling Windows Updates with PowerShell (Remove-WindowsUpdate)
You can use the Remove-WindowsUpdate cmdlet to correctly uninstall the updates with PowerShell. Just specify the KB number as an argument of the KBArticleID parameter. To delay automatic computer restart, add the –NoRestart option:
Remove-WindowsUpdate -KBArticleID KB4489873 -NoRestart
How to Hide Windows Updates with PowerShell?
You can hide the specific updates so they will be never installed by the Windows Update service on your computer (most often you need to hide the driver updates). For example, to hide the KB4489873 and KB4489243 updates, run these commands:
$HideList = "KB4489873", "KB4489243"
Get-WindowsUpdate -KBArticleID $HideList –Hide
Now the next time you scan for updates using the Get-WUlist command, the hidden updates won’t be displayed in the list of updates available for installation.
This is how you can display the list of updates hidden on this computer:
Get-WindowsUpdate –IsHidden
Notice that the H
(Hidden) attribute has appeared in the Status column of hidden updates.
To unhide some updates, run this command:
Get-WindowsUpdate -KBArticleID $HideList -WithHidden -Hide:$false
or:
Show-WindowsUpdate -KBArticleID $HideList
For those who feel uncomfortable in the PowerShell console, I would recommend a graphic Windows Update MiniTool to manage updates in Windows 10/11 and Windows Server 2022/2019.