Для управления обновлениями Windows можно использовать PowerShell модуль PSWindowsUpdate. Модуль PSWindowsUpdate доступен для загрузки из PowerShell Gallery и позволяет администратору просканировать, скачать, установить, удалить или скрыть обновления на локальном или удаленных рабочих станциях и серверах Windows.
Содержание:
- Установка модуля управления обновлениями PSWindowsUpdate
- Сканировать и загрузить обновления Windows с помощью PowerShell
- Установка обновлений Windows с помощью команды Install-WindowsUpdate
- >Просмотр истории установленных обновлений в Windows
- Удаление обновлений в Windows с помощью PowerShell
- Скрыть ненужные обновления Windows с помощью PowerShell
- Управление обновлениями Windows на удаленных компьютерах через PowerShell
Установка модуля управления обновлениями PSWindowsUpdate
В современных версиях Windows 10/11 и Windows Server 2022/2019/2016 модуль PSWindowsUpdate можно установить из онлайн репозитория PowerShell Gallery с помощью команды:
Install-Module -Name PSWindowsUpdate
Подтвердите добавление репозитариев, нажав Y. Проверьте, что модуль управлениям обновлениями установлен в Windows:
Get-Package -Name PSWindowsUpdate
- В изолированной среде модуль PSWindowsUpdate можно установить в офлайн режиме;
- В старых версиях Windows для использования модуля нужно предварительно обновить версию PowerShell.
Можно удаленно установить PSWindowsUpdate на другие компьютеры в сети. Следующая команда скопирует файлы модуля на указанные компьютеры (для доступа к удаленным компьютерам используется WinRM).
$Targets = "srv1.winitpro.loc", "srv2.winitpro.loc"
Update-WUModule -ComputerName $Targets -local
Политика выполнения PowerShell скриптов в Windows по умолчанию блокирует запуск командлетов из сторонних модулей, в том числе PSWindowsUpdate. Чтобы разрешить запуск любых локальных скриптов, выполните команду:
Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force
Либо вы можете разрешить запускать команды модуля в текущей сессии PowerShell:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
Импортируйте модуль в сессию PowerShell:
Import-Module PSWindowsUpdate
Выведите список доступных командлетов:
Get-command -module PSWindowsUpdate
Проверить текущие настройки клиента 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.
Сканировать и загрузить обновления Windows с помощью PowerShell
Чтобы просканировать компьютер на сервере обновлений и вывести список обновлений, которые ему требуется, выполните команду:
Get-WindowsUpdate
или
Get-WUList
Команда должна вывести список обновлений, которые нужно установить на вашем компьютере.
Команда Get-WindowsUpdate при первом запуске может вернуть ошибку:
Value does not fall within the expected range.
Для исправления ошибки нужно сбросить настройки агента Windows Update, перерегистрировать библиотеки и восстановить исходное состояние службы wususerv с помощью команды:
Reset-WUComponents -Verbose
Чтобы проверить, откуда получает ли Windows обновлений с серверов Windows Update в Интернете или локального WSUS, выполните команду:
Get-WUServiceManager
В этом примере вы видите, компьютер настроен на получение обновлений с локального сервера 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
Чтобы убрать определенные продукты или конкретные KB из списка обновлений, которые получает ваш компьютер, вы их можете исключить по:
- Категории (-NotCategory);
- Названию (-NotTitle);
- Номеру обновления (-NotKBArticleID).
Например, чтобы исключить из списка обновления драйверов, OneDrive, и одну конкретную KB:
Get-WUlist -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4533002
Скачать все доступные обновления на компьютер (обновления загружаются в локальный кэш обновлений в каталоге
C:\Windows\SoftwareDistribution\Download
).
Get-WindowsUpdate -Download -AcceptAll
Windows загрузит все доступные патчи сервера обновлений (MSU и CAB файлы) в локальный каталог обновлений, но не запустит их автоматическую установку.
Установка обновлений 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
Проверить, нужна ли перезагрузка компьютеру после установки обновления (атрибуты RebootRequired и RebootScheduled):
Get-WURebootStatus
>Просмотр истории установленных обновлений в Windows
С помощью команды Get-WUHistory вы можете получить список обновлений, установленных на компьютере ранее автоматически или вручную.
Можно получить информацию о дате установки конкретного обновления:
Get-WUHistory| Where-Object {$_.Title -match "KB4517389"} | Select-Object *|ft
Вывести даты последнего сканирования и установки обновлении на компьютере:
Get-WULastResults |select LastSearchSuccessDate, LastInstallationSuccessDate
Удаление обновлений в Windows с помощью PowerShell
Для корректного удаления обновления Windows используется командлет Remove-WindowsUpdate. Вам достаточно указать номер KB в качестве аргумента параметра KBArticleID.
Remove-WindowsUpdate -KBArticleID KB4011634
Скрыть ненужные обновления Windows с помощью PowerShell
Вы можете скрыть определенные обновления, чтобы они никогда не устанавливались службой обновлений Windows Update на вашем компьютер (чаще всего скрывают обновления драйверов). Например, чтобы скрыть обновления KB2538243 и KB4524570, выполните такие команды:
$HideList = "KB2538243", "KB4524570"
Get-WindowsUpdate -KBArticleID $HideList -Hide
или используйте alias:
Hide-WindowsUpdate -KBArticleID $HideList -Verbose
Теперь при следующем сканировании обновлений с помощью команды Get-WindowsUpdate скрытые обновления не будут отображаться в списке доступных для установки.
Вывести список скрытых обновлений:
Get-WindowsUpdate –IsHidden
Обратите внимание, что в колонке Status у скрытых обновлений появился атрибут H (Hidden).
Отменить скрытие обновлений можно так:
Get-WindowsUpdate -KBArticleID $HideList -WithHidden -Hide:$false
или так:
Show-WindowsUpdate -KBArticleID $HideList
Управление обновлениями Windows на удаленных компьютерах через PowerShell
Практически все командлеты модуля PSWindowsUpdate позволяют управлять обновлеями на удаленных компьютерах. Для этого используется атрибут
-Computername Host1, Host2, Host3
. На удаленных компьютерах должен быть включен и настроен WinRM (вручную или через GPO). Модуль 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
С помощью Invoke-Command можно разрешить использовать модуль PSWindowsUpdate на удаленных компьютерах и открыть необходимые порты в Windows Defender Firewall (команда
Enable-WURemoting
):
Invoke-Command -ComputerName $computer -ScriptBlock {Set-ExecutionPolicy RemoteSigned -force }
Invoke-Command -ComputerName $computer -ScriptBlock {Import-Module PSWindowsUpdate; Enable-WURemoting}
Проверить список доступных обновлений на удаленном компьютере:
Get-WUList –ComputerName server2
Скачать и установить все доступные обновлений на нескольких удаленных серверах:
$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)
Проверить статус задания установки обновлений:
Get-WUJob -ComputerName $ServerNames
Если команда вернет пустой список, значит задача установки на всех компьютерах выполнена.
Проверьте наличие обновления на нескольких удаленных компьютерах:
"server1","server2" | Get-WUHistory| Where-Object {$_.Title -match "KB4011634"} | Select-Object *|ft
Получить дату последней установки обновлений на всех компьютерах в домене можно с помощью командлета 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
}
PowerShell модуль PSWindowsUpdate удобно использовать для загрузки и установки обновлений Windows из командной строки (единственный доступны вариант в случае установки обновлений на хосты без графического интерфейса: Windows Server Core и Hyper-V Server). Также этот модуль незаменим, когда нужно одновременно запустить и проконтролировать установку обновлений сразу на множестве серверов/рабочих станциях Windows.
Начиная с версии Windows 10 1709, PowerShell обзавелся несколькими командлетами позволяющими выполнить установку обновлений.
Содержание
- Проверка Наличия Обновлений
- Установка Доступных Обновлений
- Дополнительные Командлеты
- Итог
Проверка Наличия Обновлений
Прежде чем выполнить обновление, нужно убедиться в их наличии. Дальнейшие действия предполагают, что командная оболочка PowerShell была запущена от имени администратора (Win+X, выбрать в открывшемся меню пункт Windows PowerShell (администратор)).
Выполняем проверку наличия новых обновлений.
Start-WUScan
Если выполнение команды завершилось выводом списка обновлений, то значит данные обновления в системе отсутствуют. В противном случае обновлений необходимых для установки нет.
Установка Доступных Обновлений
Установка ранне найденных обновлений выполняется командлетом Install-WUUpdates. Но простой запуск данного командлета ничего не даст. Так же как и подстановка UpdateID в качестве аргумента.
В качестве аргумента командлет Install-WUUpdates ожидает массив объектов типа Microsoft.Management.Infrastructure.CimInstance[], или же любой другой объект который можно привести к данному типу.
Получить подходящий объект можно из вывода командлета Start-WUScan.
$wu = Start-WUScan
Переменная $wu в данном случае будет содержать массив объектов CimInstance. Как раз то, что необходимо командлету Install-WUUpdates.
Install-WUUpdates $wu
Учитывая все вышесказанное составим итоговую команду выполнения установки обновлений.
$wu = Start-WUScan; if ($wu) {$wu; Install-WUUpdates $wu} else {echo "Обновлений пока нет! :)"}
Данная команда запускает процесс получения списка обновлений в переменную $wu, и если список не пуст, то запускается командлет Install-WUUpdates с переданным списком ей списком $wu в качестве аргумента.
Запуск данной команды, при отсутствии доступных обновлений завершится соответствующим сообщением.
Выполнение процедуры по отдельности будет выглядеть следующим образом.
# Выпоолняем получение списка обновлений в переменную $wu
$wu = Start-WUScan
# Выводим содержимое переменной $wu чтобы убедиться в наличии в ней данных (обновлений)
$wu
# Выполняем установку обновлений при условии что переменная $wu не пуста
Install-WUUpdates $wu
Дополнительные Командлеты
Get-WUIsPendingReboot — проверяет, необходимо ли выполнять перезагрузку операционной системы после выполнения процедуры обновления. Возможные варианты вывода True (перезагрузка необходима) или False (перезагружать не нужно).
Get-WULastScanSuccessDate — выводит дату последнего сканирования обновлений выполненного через Центр обновления Windows.
Get-WULastInstallationDate — выводит дату последней установки обновлений выполненных через Центр обновления Windows.
Install-WUUpdates -DownloadOnly … — выполняет загрузку указанного списка обновлений без установки.
Итог
Темы освещенные в данной статье: Как выполнить обновление Windows 10 последних редакций штатными средствами через PowerShell. Как выполнить проверку наличия обновлений Windows 10 в PowerShell. Как выполнить установку обновлений командлетом Install-WUUpdates.
- To install updates on Windows 10 from PowerShell, open “PowerShell (admin),” run the “Install-Module PSWindowsUpdate” command to install the module, “Get-WindowsUpdate” to view available updates, and “Install-WindowsUpdate” to install all the cumulative updates.
- To download, install, and reboot Windows 10, open “PowerShell (admin)” and run the “Get-WindowsUpdate -AcceptAll -Install -AutoReboot” command.
- The “Get-WindowsUpdate -Install -KBArticleID ‘KB5031445′” command allows you to install a specific Windows 10 update.
UPDATED 11/8/2023: Windows 10 updates happen automatically or manually through the Windows Update settings. However, if you try to patch a new installation or create a custom script to automate the process, you can use commands to download and install missing patches with the “PSWindowsUpdate” module on PowerShell.
Michal Gajda has created the PSWindowsUpdate module, and it’s available through the PowerShell Gallery. It includes the components to make it easy to check, download, and install updates on Windows 10.
In this guide, I will teach you the steps to check and install updates for Windows 10 using PowerShell.
- Update Windows 10 from PowerShell
- Manage updates with PowerShell
To check and install updates with PowerShell, use these steps:
-
Open Start on Windows 10.
-
Search for PowerShell, right-click the top result, and select the Run as administrator option.
-
Type the following command to install the module to run Windows Update and press Enter:
Install-Module PSWindowsUpdate
Quick note: After installing the module, you no longer need to repeat step No. 3 to use the module and manage updates.
-
Type A and press Enter to confirm.
-
Type the following command to check for updates with PowerShell and press Enter:
Get-WindowsUpdate
-
Type the following command to install the available Windows 10 updates and press Enter:
Install-WindowsUpdate
-
Type A and press Enter to confirm.
Once you complete the steps, the latest cumulative updates will be downloaded and installed on your computer.
Manage updates with PowerShell
The PSWindowsUpdate module includes many options to manage updates. You can always use the Get-Command –Module PSWindowsUpdate
command to query a list of the available commands.
1. Auto reboot system after update command
To download, install, and then reboot the computer to complete the update process, use these steps:
-
Open Start.
-
Search for PowerShell, right-click the top result, and select the Run as administrator option.
-
Type the following command to download and install all the available updates, reboot the system, and press Enter:
Get-WindowsUpdate -AcceptAll -Install -AutoReboot
After completing the steps, Windows 10 will download and install all the available updates, rebooting the computer to apply the changes automatically.
2. Download a specific update command
To download and install a specific update on Windows 10 from PowerShell, use these steps:
-
Open Start.
-
Search for PowerShell, right-click the top result, and select the Run as administrator option.
-
Type the following command to list the available updates along with their KB numbers with PowerShell and press Enter:
Get-WindowsUpdate
-
Type the following command to download, install a specific update, reboot the system, and press Enter:
Get-WindowsUpdate -Install -KBArticleID 'KB5031445'
In the command, replace “KB5031445” with the KB name of the update you want to install.
Once you complete the steps, in this case, Windows 10 will download and install update KB5031445 on your device.
Windows 10 comes with the Windows Update Provider but has limited options compared to the PSWindowsUpdate module and is more complicated to use.
Update November 8, 2023: This guide has been updated to ensure accuracy and reflect changes.
Why You Can Trust Pureinfotech
The author combines expert insights with user-centric guidance, rigorously researching and testing to ensure you receive trustworthy, easy-to-follow tech guides. Review the publishing process.
There are several ways out there to update our operating system including Windows Update, Microsoft Update Catalog, and WSUS. Each one of these processes has its own limitations and so does this method which we are going to discuss in this tutorial. However, if you love using Command-line terminals, you will surely love installing Windows 10 Updates using PowerShell Scripts.
Well, in this method, all you require is to install a module first i.e. PSWindowsUpdate. After you install this module on your computer, you may run a simple script to automate the Windows Update process on your PC. This module not only allows installing pending updates but also supports a wide range of options like hiding buggy updates, installing Tuesday patches, and many more. Let’s explore how to use this tool in detail –
There are numerous ways out there to update Windows 10. However, in this post, we will look at how to install updates using the command-line terminal i.e. PowerShell. To do so, use these steps –
- Press Windows Key and X to open the Power Menu.
- Select Windows PowerShell (Admin).
- When User Account Control prompts, hit Yes.
- Doing so will launch the PowerShell having administrative rights.
- On the elevated console, execute the command below –
Install-Module PSWindowsUpdate
- This code will run and ask for your permissions to install any further module. If so, type “Y” or “A” to accept it, and press Enter.
- Now that you have installed the required module on your PC, run this code next –
Get-WindowsUpdate
Note: You may start getting into error messages. Worry not as this is appearing just because Microsoft doesn’t allow local PowerShell Scripts to run by default on Windows 10. However, there is a way out there to edit the required setting and re-enable installing scripts locally on your device.
- You will get a list of updates that are pending on your computer.
- Next, execute the command below –
Install-WindowsUpdate
- You will be asked to give your consent before this module starts downloading and installing the pending updates on your PC. Type “A” to accept all, or Y to accept a particular request, and hit Enter.
- The whole installing process might take several minutes depending upon your net connectivity, so wait patiently.
- Once this is over, your PC is upgraded to the latest cumulative update.
How to Manage Windows 10 Updates using PowerShell
Apart from updating Windows 10, the PSWindowsUpdate Module may perform a wide variety of operations. A few of them include hiding buggy updates, install app updates, download and install any specific security patch, etc.
Note: You need to install the “PSWindowsUpdate” module only once.
- To download, install, and reboot your PC after installing all pending updates, use this code –
Get-WindowsUpdate -AcceptAll -Install -AutoReboot
When you execute the above code, this will look out for pending updates online, get your consent for all, install them, and at last reboot your computer.
- Following this way, you may also look for any Tuesday patch update available for your operating system. To do so, run “Get-WindowsUpdate” first, and when you get the KB number of the latest security patch, run this code –
Get-WindowsUpdate -Install -KBArticleID 'KBNumber'
Note: Make sure to replace the KBNumber with the actual cumulative update number.
- If you want to hide an update popping up every now and then on your device, run these two codes one after another.
Get-WindowsUpdate
Hide-WindowsUpdate -KBArticleID KBNUMBER
Tip: Make sure to replace the KBNumber with the exact cumulative update number that you get after running the first command.
I hope you find this article helpful and find it useful to install pending updates by running PowerShell Scripts. If you do have any queries or suggestions, let us know in the comment section below.
,
If you want to run Windows Update from Command Prompt or PowerShell in Windows 10/11, continue reading below.
Microsoft releases updates regularly to enhance security, fix bugs, and introduce new features that improve the functionality of Windows devices.
Windows updates are divided into 2 categories: Quality updates, which are constantly released for security reasons and to fix glitches, and Feature updates, which offer improved versions and additional features.
The usual way to update Windows 10/11 is by going to Settings > Update & Security and to check and install updates, but in some cases may needed to install updates from the command line or PowerShell if the usual way doesn’t work.
This tutorial contains instructions on how run Windows Update and install or uninstall Updates with commands in Command Prompt & PowerShell.
How to Check and Install Updates from PowerShell or Command Prompt in Windows 10/11 & Server 2016/2019.
- Part 1. Install Updates from Command Line.
- Part 2. Install Updates from PowerShell.
- Part 3. Uninstall Updates from PowerShell.
Part 1. How to Run Windows Update from Command Prompt.
In previous versions of Windows you could update Windows using the command «wuauclt /detectnow /updatenow».
In latest Windows 10 versions the command ‘WUAUCLT.EXE’ does not work anymore and has been replaced by the command ‘USOCLIENT.EXE’.
Info: The ‘USOCLIENT.EXE’ is the Update Session Orchestrator client that used to download and install Windows Updates. *
* Notes:
1. According to reports, not all Windows 10 and 11 versions support the USOCLIENT. If the same is true for your device, update your system using the PowerShell method.
2. Since USOCLIENT commands do not display anything on the screen at the time they are executed, the only way to determine if the command is working is to look at the events in the following destinations.
- C:\Windows\SoftwareDistribution\ReportingEvents.log
- Task Scheduler -> Microsoft -> Windows -> Update Orchestrator
To install updates with ‘USOCLIENT.EXE’, follow these steps:
1. Launch Command Prompt or PowerShell as an Administrator and ask Yes at the UAC prompt.
2. Force Windows to Check for Updates with one of the following commands: *
-
- UsoClient StartScan
- USOClient.exe StartInteractiveScan
* Note: Some users reported that in their case one command worked and not the other. To see which of the 2 commands works in your case open Windows Update at the same time as running the command to make sure that Windows is checking for updates.
3. After finding Updates, download them with one of the following commands:
-
- UsoClient StartDownload
- ScanInstallWait
4. Proceed to install downloaded updates with this command:
- UsoClient StartInstall
5. When the updates installed, reboot your pc with this command: *
- UsoClient RestartDevice
* Note: I suggest to wait at least 30 minutes before restarting your PC.
Part 2. How to Run Windows Update from PowerShell in Windows 10/11.
If you want to download and install Windows or Drivers updates using PowerShell commands, use the instructions below.
To Install Windows Updates from PowerShell:
1. Open PowerShell as Administrator.
2. Proceed and install the ‘PowerShell Windows Update module’ with this command and ask Yes (press ‘y’), when prompted to install any other provider needed: *
- Install-Module PSWindowsUpdate
* Notes:
1. The ‘PSWindowsUpdate’ is a necessary module to install updates from PowerShell. To see all the commands available in the module, give this command:
- Get-Command -module PSWindowsUpdate
2. By default the module only look for Windows and driver updates. If you have other Microsoft Products installed (e.g. Office), and you want to get updates for them too, give also this command:
- Add-WUServiceManager -MicrosoftUpdate
3. Then give the following command to allow the execution of scripts on your machine and ask Yes at the warning when prompted.
- Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
4. Now force Windows to download and list all available updates in PowerShell. *
- Get-WindowsUpdate
5. Now proceed according to what you want:
A. To install all available Windows Updates from PowerShell give this command:
- Install-WindowsUpdate
B. To install all available Windows Updates and the updates for all other Microsoft Products, give this command:
- Install-WindowsUpdate -MicrosoftUpdate
C. To install a specific Windows Update from PowerShell, give this command and ask Yes (y) when prompted: *
- Get-WindowsUpdate -KBArticleID «KB-Number” -Install
e.g. to install the KB5005463 in this example:
- Get-WindowsUpdate -KBArticleID «KB5005463» -Install
D. To prevent a Windows Update from being installed, give this command in PowerShell:
- Get-WindowsUpdate -NotKBArticle “KB-Number” -AcceptAll
e.g. to prevent the installation of the KB5005463 in this example:
- Get-WindowsUpdate -NotKBArticle “KB5005463” -AcceptAll
E. To exclude specific categories from updating, (e.g. the «Driver updates or the Feature updates, give this command:
- Install-WindowsUpdate -NotCategory «Drivers»,»FeaturePacks» -AcceptAll
Part 3. How to Uninstall Windows Updates from PowerShell.
To remove Updates using PowerShell:
1. Open PowerShell as Administrator.
2. In the PowerShell window, give the following command to get a list of all installed updates.
- wmic qfe list brief /format:table
2. Take note of the KB number associated with the Windows Update you wish to remove.
3. Now execute the following command to remove the desired update in PowerShell:
- wusa /uninstall /kb:Number
Note: Replace ‘Number’ with the KB number of the update you want to remove. For example: to remove the KB5005635 give this command:
- wusa /uninstall /kb:5005635
That’s it! Which method worked for you?
Let me know if this guide has helped you by leaving your comment about your experience. Please like and share this guide to help others.
If this article was useful for you, please consider supporting us by making a donation. Even $1 can a make a huge difference for us in our effort to continue to help others while keeping this site free:
- Author
- Recent Posts
Konstantinos is the founder and administrator of Wintips.org. Since 1995 he works and provides IT support as a computer and network expert to individuals and large companies. He is specialized in solving problems related to Windows or other Microsoft products (Windows Server, Office, Microsoft 365, etc.).