Для управления обновлениями 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.
Are you facing a problem in updating Windows 10 via a graphical user interface? Yes, then try the command line force update method to download and install them.
As we know on Windows 10, we can opt for slow and fast rings build that let the Windows insiders get the latest updates even before they went to public. However, because of a few betas and frequently issuing of updates by Microsoft, sometimes users may face some problems in updating Windows 10 using the traditions method from the Check for Update Settings.
I am saying this because recently my Windows 10 PC got some updates and every time it asked me to restart the laptop to install updates but it couldn’t. Thus, in such case, we can use the Command line to force the Windows 10 system to download and install the latest updates manually using Powershell or Command Prompt. I recommend the Powershell.
Force Windows 10 to Update using PSwindowsupdate Command-line
Tip: Before going further to follow the given steps I would like to recommend you: Go to your Windows 10 installation drive which is generally the C: drive, there click on the Windows folder and open the SoftwareDistribution inside that open Download and delete all files resides in it.
Windows 10 force update using PowerShell
- Power shell is the native and advanced command-line tool of Windows platform. Just right click on the Windows 10 start button and select Windows Powershell (Admin).
- In the Powershell first, to install the Windows Update Module, for that use the command:
Install-Module PSWindowsUpdate
The output for the above command:
NuGet provider is required to continue
PowerShellGet requires NuGet provider version 'x.x.x" or newe to interact with NuGet-based repositories. The NuGet provider must be available in "C:\Program files\PackageManagement\ProviderAssemblies' or C:'Users\Trm\AppData\localPackahemanagement\ProviderAssemblies'. You can also install the NuGet provider by running install-PackageProvider - Name BuGet -MinimumVersion x.x.x -force'. DO you want PowershellGet to install and import the NuGet provider now?
[Y] Yes [N} No [S] Suspend [?] Help (default is "Y"): Y
Trusted repository
You install the modules from an untrusted repository. If you trust this repository, change its installation policy value by running the Set PSRespository cmdlet. Are you sure you want to install the modules from PSGalery'?
[Y] Yes [A] Yess to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): Y
- Check the latest available updates for Windows 10 using the command:
Get-Windowsupdate
If you receive an error:
PS C:\WINDOWS\system32> Get-WindowsUpdate
Get-WindowsUpdate : The 'Get-WindowsUpdate' command was found in the module 'PSWindowsUpdate', but the module could
not be loaded. For more information, run 'Import-Module PSWindowsUpdate'.
At line:1 char:2
+ Get-WindowsUpdate
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-WindowsUpdate:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CouldNotAutoloadMatchingModulePowershell Script running error
- To solve it, on Windows 10 search bar simply type Script and an option “Allow local PowerShell scripts to run without signing” will appear, click on the open.
Allow Powershell local script running without signing This will drop you in the For Developers section of Windows 10. Select the PowerShell option Apply the following settings to execute PowerShell Scripts. “Change execution policy to allow local PowerShell scripts to run without signing. Require signing for remote scripts.“And click on the Apply button.
allow local scripts on Powershell windows 10 Now close the PowerShell and run again as admin. After that use the command:
Get-Windowsupdate
- Finally, type the Powershell script command to install windows updates and then reboot. It will allow the Windows to connect, downloading and installing of the updates-
Install-WindowsUpdate
The command will first ask your permission and perform the force update. Once it finishes, the PowerShell will prompt to reboot the Windows 10 system for proper installation of updates.Force Update Windows 10 using the command line
Apart from the PowerShell method, one can also go for the Command Prompt, for that simply run it as Administrator on Windows 10.
To check and get the updates – UsoClient StartDownload
and to install the same the command will be UsoClient StartInstall
.
A single command for all three tasks is UsoClient ScanInstallWait
Once done restart the device for implementing the updates – UsoClient RestartDevice
Other Articles:
- Add-apt-repository command not found error- Solved Ubuntu/Kali
- Best Linux Ubuntu Cleaner software to clean system disk, apt…
- What are checksums? How to find the checksum of a file? All you need to know
To force a Windows update using PowerShell, you can use the following command which triggers the update process on your system.
Get-WindowsUpdate -Install -AcceptAll
Understanding Windows Update
What is Windows Update?
Windows Update is a Microsoft service that provides updates for Windows operating systems and other Microsoft software. It plays a crucial role in system maintenance, enhancing security, improving performance, and introducing new features. Keeping Windows updated ensures that you have the latest protections against vulnerabilities, bugs, and potential threats.
Why Use PowerShell for Windows Updates?
While Windows Update can be managed through the graphical interface, using PowerShell offers several significant advantages. PowerShell allows users to automate tasks, manage updates remotely, and execute commands in batch processes, making it an effective tool for IT professionals and system administrators.
In situations where traditional methods may involve multiple clicks or require setting adjustments, PowerShell provides a straightforward command-line approach that can simplify and expedite the update process.
Install Windows Updates PowerShell: A Simple Guide
Preparing for Windows Update with PowerShell
Checking Windows Update Settings
Before forcing a Windows update, it’s essential to verify your update settings to ensure that updates can be downloaded and installed without hindErances. You can view your current Windows Update policy by running the following PowerShell command:
Get-WindowsUpdatePolicy
This command will display the settings applied to your system, including whether updates are automatically installed or if waiting for user intervention.
Installing Required Modules
To manage Windows updates through PowerShell effectively, you may need to install the `PSWindowsUpdate` module. This module is designed specifically for handling updates more conveniently. To install the module, you can use:
Install-Module -Name PSWindowsUpdate -Force
Ensure that you run PowerShell with administrative privileges to avoid permission errors during installation.
Understanding Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
How to Force Windows Updates with PowerShell
Using the PSWindowsUpdate Module
Once the `PSWindowsUpdate` module is in place, you can easily force your system to check for updates. Use the command:
Get-WindowsUpdate
This command will search for available updates for your machine. It retrieves a list of potential updates without installing them, allowing you to assess what needs to be done.
Forcing the Installation of Updates
To install all available updates immediately, you can execute the following command:
Install-WindowsUpdate -AcceptAll -AutoReboot
The `-AcceptAll` parameter installs all updates without requiring additional confirmations, while `-AutoReboot` allows your system to restart automatically if required to complete the installation. Understanding these parameters is vital as they save time and streamline the update process.
Checking the Update History
After installing updates, you may want to review what has been applied to your system. By running the following command, you can view the history of installed updates:
Get-WindowsUpdateLog
This command generates a detailed log of updates processed, which can help in tracing any issues or simply keeping a record of what changes have taken place on your machine.
Mastering Microsoft.PowerShell.Commands.WriteErrorException
Additional PowerShell Commands for Windows Update
Forcing Updates to Specific Components
Sometimes, you may want to install a specific update rather than all available updates. By knowing the specific KB (Knowledge Base) number of the update you wish to install, you can run the following command:
Install-WindowsUpdate -KBArticleID "KBXXXXXX"
Replace `KBXXXXXX` with the actual KB number of the update. This targeted approach is useful for addressing specific issues that a particular update resolves.
Scheduling Windows Updates with PowerShell
To automate Windows updates, consider using Task Scheduler to create a scheduled task that runs your PowerShell scripts at specified intervals. Here’s a brief outline of how you can schedule updates using PowerShell commands:
- Write a script that includes the PowerShell commands for checking and installing updates.
- Use Task Scheduler to create a new task and set the trigger to your preferred time (e.g., daily or weekly).
- In the action section of the task, point it to your PowerShell script.
This automation ensures your system is updated regularly without manual intervention, maintaining security and performance.
Invoke-PowerShell: Mastering Command Execution Effortlessly
Troubleshooting Windows Update Issues
Common Issues When Using PowerShell for Updates
At times, users may encounter various issues while attempting to force updates via PowerShell. Some common problems include:
- The Windows Update service may be paused or disabled.
- Network connectivity issues might prevent update downloads.
- Conflicting applications or settings could block updates.
In these cases, troubleshooting steps may range from ensuring adequate internet connectivity to checking the Windows Update service status using:
Get-Service -Name wuauserv
Resetting Windows Update Components
If you continue to face issues, it might be beneficial to reset Windows Update components. You can do this by executing the following commands:
Get-Service wuauserv, cryptSvc, bits, msiserver | Stop-Service -Force
Get-Service wuauserv, cryptSvc, bits, msiserver | Set-Service -StartupType Manual
These commands stop the necessary services, allowing you to reset components and prepare your system for a fresh start with updates.
Mastering Wget in Windows PowerShell for Easy Downloads
Conclusion
Using PowerShell to force Windows updates provides a powerful alternative to traditional update methods, delivering efficiency and control. Commands like `Install-WindowsUpdate` and `Get-WindowsUpdate` allow for tailored management of updates that can save time and enhance security.
By incorporating the techniques outlined, you can ensure your Windows operating system is consistently up-to-date and running smoothly. Dive into PowerShell’s capabilities today, and enjoy a more streamlined update process.
Начиная с версии 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.
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:
-
Open Command Prompt with administrative privileges
-
Run wuauclt /detectnow to check for new updates and download them
wuauclt /detectnow
-
Run wuauclt /updatenow to install updates
wuauclt /updatenow
-
(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:
-
Start checking for new updates
UsoClient /StartScan
-
Start downloading updates
UsoClient /StartDownload
-
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.
-
Open the Run Command box (Windows key + R).
-
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
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:
-
Run the following command to install PSWindowsUpdate:
Install-Module PSWindowsUpdate
Install PSWindowsUpdate module -
Check for available updates by running this cmdlet:
Get-WindowsUpdate
Check for available Windows updates -
Now install these updates using this cmdlet:
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:
-
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.
-
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:
-
Navigate to:
-
In Windows 11:
Settings app >> Windows Update
-
In Windows 10:
Settings app >> Update & Security >> Windows Update
-
-
Click “Check for updates.”
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.
-
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.
-
Select and delete all the files from the “Download” folder.
Delete all files in the “Download” folder -
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:
-
Go to http://www.wuinstall.com/ and install the latest free version of Wuinstall on your computer.
-
Open an elevated Command Prompt.
-
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.
-
To download the updates, run the following command:
wuinstall /download
This will download all the available updates from Microsoft servers.
-
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:
-
Launch the Command Prompt.
-
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.