Как запустить обновление windows 10 вручную через powershell

Для управления обновлениями 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

Установить powershell модуль 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

список командлетов модуля pswindowupdate

Проверить текущие настройки клиента 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 - Get-WUSettings

В данном примере клиент Windows Update на компьютере настроен с помощью GPO на получение обновлений с локального сервера обновлений WSUS.

Сканировать и загрузить обновления Windows с помощью PowerShell

Чтобы просканировать компьютер на сервере обновлений и вывести список обновлений, которые ему требуется, выполните команду:

Get-WindowsUpdate

или

Get-WUList

Команда должна вывести список обновлений, которые нужно установить на вашем компьютере.

Поиск (сканирование) доступных обновлений windows: get-windowsupdate

Команда Get-WindowsUpdate при первом запуске может вернуть ошибку:

Value does not fall within the expected range.

Ошибка Get-WindowsUpdate - Value does not fall within the expected range.

Для исправления ошибки нужно сбросить настройки агента Windows Update, перерегистрировать библиотеки и восстановить исходное состояние службы wususerv с помощью команды:

Reset-WUComponents -Verbose

Чтобы проверить, откуда получает ли Windows обновлений с серверов Windows Update в Интернете или локального WSUS, выполните команду:

Get-WUServiceManager

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 файлы) в локальный каталог обновлений, но не запустит их автоматическую установку.

Get-WindowsUpdate скачать доступные обновления на диск

Установка обновлений 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 установка обновлений windows с помощью powershell

Если вы хотите пропустить некоторые обновления при установке, выполните:

Install-WindowsUpdate -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll -IgnoreReboot

Проверить, нужна ли перезагрузка компьютеру после установки обновления (атрибуты RebootRequired и RebootScheduled):

Get-WURebootStatus

Get-WURebootStatus нужна ли перезагрузка Windows после установки обновлений

>Просмотр истории установленных обновлений в Windows

С помощью команды Get-WUHistory вы можете получить список обновлений, установленных на компьютере ранее автоматически или вручную.

Get-WUHistory - история установки обновлений

Можно получить информацию о дате установки конкретного обновления:

Get-WUHistory| Where-Object {$_.Title -match "KB4517389"} | Select-Object *|ft

Get-WUHistory найти установленные обновления

Вывести даты последнего сканирования и установки обновлении на компьютере:

Get-WULastResults |select LastSearchSuccessDate, LastInstallationSuccessDate

Get-WULastResults время последней установки обновлений в Windows

Удаление обновлений в 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

Hide-WindowsUpdate - скрыть обновление, запретить установку

Теперь при следующем сканировании обновлений с помощью команды Get-WindowsUpdate скрытые обновления не будут отображаться в списке доступных для установки.

Вывести список скрытых обновлений:

Get-WindowsUpdate –IsHidden

Обратите внимание, что в колонке Status у скрытых обновлений появился атрибут H (Hidden).

Get-WindowsUpdate –IsHidden отобразить скрытые обновления windows

Отменить скрытие обновлений можно так:

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.

,

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.

How to Run Windows Update from Command Prompt or PowerShell in Windows 10/11

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: *

    1. UsoClient StartScan
    2. 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.

Check for Updates command

3. After finding Updates, download them with one of the following commands:

    1. UsoClient StartDownload
    2. 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.

install updates command prompt

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

How to Run Windows Update from PowerShell

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

allow scripts execution

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

install windows updates powershell


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

install specific windows update powershell


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

hide windows update powershell


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

How to view Installed Windows Updates from PowerShell

2. Take note of the KB number associated with the Windows Update you wish to remove.

View List of Installed Updates - PowerShell

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

How to uninstall Windows Updates from PowerShell

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.).

  • 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:

  1. Open Start on Windows 10.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to install the module to run Windows Update and press Enter:

    Install-Module PSWindowsUpdate

    Install PSWindowsUpdate

    Quick note: After installing the module, you no longer need to repeat step No. 3 to use the module and manage updates.

  4. Type A and press Enter to confirm.

  5. Type the following command to check for updates with PowerShell and press Enter:

    Get-WindowsUpdate
  6. Type the following command to install the available Windows 10 updates and press Enter:

    Install-WindowsUpdate

    PowerShell install Windows 10 updates

  7. 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:

  1. Open Start.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. 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:

  1. Open Start.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to list the available updates along with their KB numbers with PowerShell and press Enter:

    Get-WindowsUpdate
    
  4. 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.

The Windows Update allows users to keep Windows OS up to date with the latest security patches, new features, and bug fixes from Microsoft. You can access Windows Update from the Settings app on your PC. You can also run Windows Update from CMD.

Windows Update runs automatically in the background and installs new updates when they are available. However, you can also manually check for updates at any time. This will help you get the latest features and improvements faster.

By checking regularly for new Windows updates, you can ensure your PC is running smoothly and securely, ensuring you are safe from viruses, malware, and other threats.

In this guide, you will learn how to run Windows Update from Command Prompt and PowerShell using different commands.

Table of Contents

Force Windows Update from CMD

Check for updates on all Windows versions

If you want to run Windows Update from Command Prompt, you can use the wuauclt.exe utility. This utility allows you to check for updates, download updates, and install updates from the command line. The only limitation of running Windows Update through the CMD is that it won’t show any progress. Only results are shown when the process is complete. Here is how to run Windows Update from CMD:

  1. Open Command Prompt with administrative privileges

  2. Run wuauclt /detectnow to check for new updates and download them

    wuauclt /detectnow

  3. Run wuauclt /updatenow to install updates

    wuauclt /updatenow
  4. (Optional) Run wuauclt /reportnow to report back to WSUS server (if available)

    wuauclt.exe /reportnow

You can also use multiple switches in the same command:

wuauclt /detectnow /updatenow

If you want to disregard the already detected updates and force Windows Update to check for updates again immediately, you may run the following command:

wuauclt /resetauthorization /detectnow

Since the command prompt does not show any progress, a better approach would be to check and install updates simultaneously. Here’s the command for this:

wuauclt /detectnow /updatenow

Check for Windows updates in Windows 11, 10

The above-mentioned command will work in all versions of Windows, including Windows 7 and Windows Server 2008 R2. But if you are using Windows 11, Windows 10 or Windows Server 2016, you can use the “UsoClient” command, which has more options than “wuauclt.” You can run UsoClient with the following switches:

  1. Start checking for new updates

    UsoClient /StartScan
  2. Start downloading updates

    UsoClient /StartDownload

  3. Start installing updates

    UsoClient /StartInstall

Force Windows Update Check using Run Command Box

I found out that the easiest way to force a Windows update check is to use a command in the Run dialog box. There are other commands from CMD and PowerShell as well, but let’s start with the easiest way to do it.

  1. Open the Run Command box (Windows key + R).

  2. Run the following command:

    control update
    Check Windows update from the Run Command box

This will trigger the Windows Update graphical user interface which will start checking for new updates. This method works on all versions of Windows including Windows 10 and Windows 11.

There is another command that will trigger the same effect but only works in Windows 10 and 11:

ms-settings:windowsupdate
Trigger Windows Update from Settings app

Run Windows Update from PowerShell

There is no official Windows Update module for PowerShell. However, you can use “PSWindowsUpdate.” PSWindowsUpdate is a third-party module that can be used to configure Windows updates in Windows.

This module is not installed in Windows by default but you can download it from the PowerShell gallery and install and run the module to check for new updates.

Here are the three steps to run Windows Update through PowerShell:

  1. Run the following command to install PSWindowsUpdate:

    Install-Module PSWindowsUpdate
    Install Module PSWindowsUpdate

    Install PSWindowsUpdate module
  2. Check for available updates by running this cmdlet:

    Get-WindowsUpdate
    Get WindowsUpdate

    Check for available Windows updates
  3. Now install these updates using this cmdlet:

    Install-WindowsUpdate
    Install WindowsUpdate

    Install available Windows updates

The above-mentioned commands will only install Windows updates. If you want to update other Microsoft products, you’ll also need to enable the Microsoft Update Service. It’s pretty easy to enable it using PowerShell:

Add-WUServiceManager -MicrosoftUpdate

If you want to automatically restart your computer after installing all the updates, you can run the following command instead:

Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot

If you don’t want to install a separate module, you can run the following command to force start Windows Update using PowerShell:

Start-Process -FilePath 'ms-settings:windowsupdate'

Deploy Updates on Remote Computers

The PSWindowsUpdate PowerShell module can also be used to deploy Windows updates on remote computers. There are two commands involved in this process:

  1. Create a list of computers and pass the list as a variable string using the computer names:

    $computer = "comp1, comp2, comp3"

    You can add more computers to the string separated by commas. Replace “compX” with the name of each computer.

  2. Run the following command to start checking for Windows updates on remote computers:

    Invoke-WUJob -ComputerName $computer -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot} -RunNow -Confirm:$false | Out-File "\server\share\logs\$computer-$(Get-Date -f yyyy-MM-dd)-MSUpdates.log" -Force

Install Specific Updates Only

If you already know the article KB no. of the specific update you want to install, you can run the following command to install that particular update(s) only:

Get-WindowsUpdate - KBArticleID "KB5002324", "KB5002325" -Install

Replace the KB number with the one you want to install.

Prevent Specific Windows Updates from Installing

You can prevent specific updates from installing on your computer by replacing the KB numbers in the following command in PowerShell:

Install-WindowsUpdate -NotKBArticle "KB5002324, KB5002325" -AcceptAll

Check for Windows Updates using Windows Settings

To check for new updates and configure your Windows Update settings, follow the steps below:

  1. Navigate to:

    • In Windows 11:

      Settings app >> Windows Update
    • In Windows 10:

      Settings app >> Update & Security >> Windows Update

  2. Click “Check for updates.”

    check for updates Windows 11

    Check for pending updates

Force Windows Update to Download Already Downloaded Updates

There will be times when the updates become corrupted or for other reasons, you just don’t want to install the downloaded updates. In that situation, you can easily delete the already-downloaded updates, which will force Windows Update to run again and check for and download the updates again.

The only caveat in this situation is that the update must not have been installed on your computer. If the update is already installed, Windows will detect it as installed and will not download it again. In that case, you will need to uninstall the update first and then force Windows Update to run again.

If you want to force Windows Update to re-download all the updates again, you can do this using the steps below.

  1. Navigate to the following directory using File Explorer:

    C:\Windows\SoftwareDistribution\Download

    This folder contains all the Windows update files that Windows OS is currently downloading or recently downloaded and installed.

  2. Select and delete all the files from the “Download” folder.

    Delete all files in Download folder

    Delete all files in the “Download” folder
  3. Run Windows Update again using the above-mentioned methods.

    This will force Windows Update to check for the same updates and download them again. The download and install process for new updates is completely automated. You don’t need to do anything during the download and installation process.

Manage Windows Updates using Wuinstall

Using WuInstall, IT Administrators can automate Windows updates. Wuinstall can be used to enforce Windows Updates inquiries, downloads, and installations at times when they deem them appropriate, enabling them to make the entire update process more controlled and user-friendly.

WuInstall is a strong and flexible system management tool that can be used in a WSUS-based or standalone environment. To download the latest updates using Wuinstall, you will need to download and install Wuinstall first. Follow the steps below:

  1. Go to http://www.wuinstall.com/ and install the latest free version of Wuinstall on your computer.

  2. Open an elevated Command Prompt.

  3. Run the following cmdlet to search for the latest available Windows updates:

    wuinstall /search

    This will not only look for new updates but will also list them in the command window.

  4. To download the updates, run the following command:

    wuinstall /download

    This will download all the available updates from Microsoft servers.

  5. To install the updates, run the following command:

    wuinstall /install

There are a few more switches that you can use with the install command:

  • /quiet – will install updates without showing anything.
  • /disableprompt – Disable any input from Windows.
  • /autoaccepteula –  Auto-accept any agreement during the update installation.
  • /rebootcycle – Install updates on the next computer reboot.

Fix Corrupted Windows Updates

Sometimes Windows Update files get corrupted and the user is not able to download the files again or install the corrupted update files. In that case, we need to run a DISM command to fix the corrupted Windows Update. Here are the steps:

  1. Launch the Command Prompt.

  2. Run the following cmdlet:

    dism.exe /Online /Cleanup-image /Restorehealth

After successfully running this command, try force downloading the updates again, and the Windows Update should start working again.

Hopefully, this will be useful in situations where you want to automate certain Windows functions. What other purposes do you want to use command line options to run Windows Update?

Run Windows Update FAQs

What is Windows Update?

Windows Update is a free Microsoft service that provides bug
fixes, security patches, and performance enhancements for Microsoft Windows operating systems. By installing these updates, users can ensure they have the latest features and security available for their operating system.

Can I use the command line to run Windows Update?

Yes, you can use Windows’ command line to run Windows Update.

What is the benefit of running Windows Update from the command line?

Running Windows Update from the command line offers flexibility,
automation, and convenience. For example, by using the command line, you can schedule updates to occur at a specific time or be triggered by an event, and even control which updates are installed.

How can I run Windows Update from the command line in Windows 10?

Follow the steps below to force Windows update with the command line:
Type cmd in the search box, choose Run as administrator, and click Yes to continue.
Type wuauclt.exe /updatenow and hit Enter.
This command will force Windows Update to check for updates and start downloading.

What is the command to run Windows Update from PowerShell?

To run Windows Update via PowerShell, enter the following command:
Start-Process -FilePath ‘ms-settings:windowsupdate’

What is “usoclient.exe” and how does it relate to Windows Update?

“Usoclient.exe” is a built-in command line tool for Windows Update that can be used to scan for updates, start updates, and even uninstall updates. It provides an alternative to Windows Update’s graphical user interface. This tool can be especially useful for IT administrators who need to run Windows Update simultaneously on multiple machines. It can be run from the command line and provides options for updating in managed environments. It also allows for more detailed control over the update process, such as setting which updates to install or uninstall.

Can Windows Update be automated using the command line?

Yes, Windows Update can be automated using the command line. This can be done by creating scripts that automatically execute Windows Update commands.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows не удалось завершить форматировать
  • Автоматическая оптимизация windows 10
  • Windows phone icon phone
  • Изменился язык в windows 8
  • Как узнать название жесткого диска на windows 11