Принудительное обновление windows 10 powershell

Вы можете использовать PowerShell модуль PSWindowsUpdate для управления обновлениями Windows из командной строки. Модуль PSWindowsUpdate не встроен в Windows и доступен для установки из репозитория PowerShell Gallery. PSWindowsUpdate позволяет администраторам удаленно проверять, устанавливать, удалять и скрывать обновления на рабочих станциях и серверах Windows. Модуль PSWindowsUpdate особо ценен при использовании для управления обновлениями в Core редакциях Windows Server (в которых отсутствуют графический интерфейс), а также при настройке образа Windows в режиме аудита.

Содержание:

  • Установка модуля управления обновлениями PSWindowsUpdate
  • Обзор команд модуля PSWindowsUpdate
  • Управление обновлениями Windows на удаленных компьютерах через PowerShell
  • Получить список доступных обновлений Windows из PowerShell
  • Установка обновлений Windows с помощью Install-WindowsUpdate
  • Просмотр истории установленных обновлений Windows (Get-WUHistory)
  • Удаление обновлений в Windows с помощью Remove-WindowsUpdate
  • Как скрыть ненужные обновления Windows с помощью PowerShell (Hide-WindowsUpdate)?

Установка модуля управления обновлениями PSWindowsUpdate

Если вы используете Windows 10/11 или Windows Server 2022/2019/2016, вы можете установить (обновить) модуль PSWindowsUpdate из онлайн репозитория через менеджер пакетов PackageManagement всего одной командой:

Install-Module -Name PSWindowsUpdate

После окончания установки нужно проверить наличие пакета:

Get-Package -Name PSWindowsUpdate

установка powershell модуля PSWindowsUpdata в Windows из галереи скриптов

В старых версиях Windows 2012R2/Windows 8.1 и ниже при установке PowerShell модуля может появится ошибка:

Install-Module: Unable to download from URI.Unable to download the list of available providers. Check your internet connection.

Для установки модуля нужно использовать для подключения протокол TLS 1.2. Включите его:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Если у вас установлена более старая версия Windows (Windows 7/8.1/ Windows Server 2008 R2/ 2012 R2) или отсутствует прямой доступ в Интернет, вы можете установить модуль PSWindowsUpdate вручную (см. полную инструкцию по офлайн установке модулей PowerShell).

  1. Скачайте модуль PSWindowsUpdate на любой онлайн компьютер:
    Save-Module –Name PSWindowsUpdate –Path C:\ps\
    ;
  2. Скопируйте модуль на целевой компьютер, и поместите его в каталог
    %WINDIR%\System32\WindowsPowerShell\v1.0\Modules
    (при постоянном использовании модуля это лучший вариант);
  3. Разрешите выполнение PowerShell скриптов:
    Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force
  4. Теперь вы можете импортировать модуль в свою сессию PowerShell:
    Import-Module PSWindowsUpdate

Примечание. В Windows 7 / Server 2008 R2 при импорте модуля PSWindowsUpdate вы можете столкнутся с ошибкой вида:
Имя "Unblock-File" не распознано как имя командлета
. Дело в том, что в модуле используются некоторые функции, которые появились только в PowerShell 3.0. Для использования этих функций вам придется обновить PowerShell, либо вручную удалить строку | Unblock-File из файла PSWindowsUpdate.psm1.

После установки модуля PSWindowsUpdate на своем компьютере вы можете удаленно установить его на другие компьютеры или сервера с помощью командлета Update-WUModule. Например, чтобы скопировать PSWindowsUpdate модуль с вашего компьютера на два удаленных сервера, выполните команды (нужен доступ к удаленным серверам по протоколу WinRM):

$Targets = "Server1", "Server2"
Update-WUModule -ComputerName $Targets -local

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

Save-Module -Name PSWindowsUpdate –Path \\fs01\ps\

Обзор команд модуля PSWindowsUpdate

Список доступных командлетов модуля можно вывести так:

get-command -module PSWindowsUpdate

Вкратце опишем назначение команд модуля:

  • Clear-WUJob – использовать Get-WUJob для вызова задания WUJob в планировщике;
  • Download-WindowsUpdate (алиас для Get-WindowsUpdate –Download) — получить список обновлений и скачать их;
  • Get-WUInstall, Install-WindowsUpdate (алиас для Get-WindowsUpdate –Install) – установить обвновления;
  • Hide-WindowsUpdate (алиас для Get-WindowsUpdate -Hide:$false) – скрыть обновление;
  • Uninstall-WindowsUpdate -удалить обновление с помощью Remove-WindowsUpdate;
  • Add-WUServiceManager – регистрация сервера обновления (Windows Update Service Manager) на компьютере;
  • Enable-WURemoting — включить правила Windows Defender файервола, разрешающие удаленное использование командлета PSWindowsUpdate;
  • Get-WindowsUpdate (Get-WUList) — выводит список обновлений, соответствующим указанным критериям, позволяет найти и установить нужное обновление. Это основной командлет модуля PSWindowsUpdate. Позволяет скачать и установить обновления с сервера WSUS или Microsoft Update. Позволяет выбрать категории обновлений, конкретные обновления и указать правила перезагрузки компьютера при установке обновлений;
  • Get-WUApiVersion – получить версию агента Windows Update Agent на компьютере;
  • Get-WUHistory – вывести список установленных обновлений (история обновлений);
  • Get-WUInstallerStatus — проверка состояния службы Windows Installer;
  • Get-WUJob – запуска заданий обновления WUJob в Task Scheduler;
  • Get-WULastResults — даты последнего поиска и установки обновлений (LastSearchSuccessDate и LastInstallationSuccessDate);
  • Get-WURebootStatus — позволяет проверить, нужна ли перезагрузка для применения конкретного обновления;
  • Get-WUServiceManager – вывод источников обновлений;
  • Get-WUSettings – получить настройки клиента Windows Update;
  • Invoke-WUJob – удаленное вызов заданий WUJobs в Task Schduler для немедленного выполнения заданий PSWindowsUpdate.
  • Remove-WindowsUpdate – удалить обновление;
  • Remove-WUServiceManager – отключить Windows Update Service Manager;
  • Set-PSWUSettings – сохранить настройки модуля PSWindowsUpdate в XML файл;
  • Set-WUSettings – настройка параметров клиента Windows Update;
  • Update-WUModule – обновить модуль PSWindowsUpdate (можно обновить модуль на удаленном компьютере, скопировав его с текущего, или обновить из PSGallery);
  • Reset-WUComponents – позволяет сбросить настройка агента Windows Update на компьютере к настройкам по-умолчанию.

список командлетов модуля 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 на компьютере настроен с помощью GPO на получение обновлений с локального сервера WSUS.

Команда
Reset-WUComponents –Verbose
позволяет сбросить все настройки агента Windows Update, перерегистрировать библиотеки и восстановить исходное состояние службы wususerv.

Reset-WUComponents сбросить настройка агента обновлений Windows

Управление обновлениями Windows на удаленных компьютерах через PowerShell

Практически все командлеты модуля PSWindowsUpdate позволяют управлять установкой обновлений на удаленных компьютерах. Для этого используется атрибут
-Computername Host1, Host2, Host3
. На удаленных компьютерах должен быть включен и настроен WinRM (вручную или через GPO).

Установите модуль PSWindowsUpdate на удаленных компьютерах и разрешите в файерволе доступ по динамическим RPC портам к процессу dllhost.exe. Можно использовать Invoke-Command для настройки модуля PSWindowsUpdate на удаленных компьютерах:

Invoke-Command -ComputerName $computer -ScriptBlock {Set-ExecutionPolicy RemoteSigned -force }
Invoke-Command -ComputerName $computer -ScriptBlock {Import-Module PSWindowsUpdate; Enable-WURemoting}

Модуль PSWindowsUpdate можно использовать для удаленного управлений обновлениями Windows как на компьютерах в домене AD, так и в рабочей группе (потребует определенной настройки PowerShell Remoting)

Для удаленного управления обновлениями компьютерах, нужно добавить имена компьютеров доверенных хостов winrm, или настроить удаленное управление PSRemoting через WinRM HTTPS:

winrm set winrm/config/client ‘@{TrustedHosts="HOST1,HOST2,…"}’

Или с помощью PowerShell:
Set-Item wsman:\localhost\client\TrustedHosts -Value wsk-w10BO1 -Force

Получить список доступных обновлений Windows из PowerShell

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

get-wulist получить список обновлений доступных для установки в windows

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

Get-WUList –ComputerName server2

Вы можете проверить, откуда должна получать обновления ваша ОС Windows. Выполните команду:

Get-WUServiceManager

ServiceID IsManaged IsDefault Name
--------- --------- --------- ----
8b24b027-1dee-babb-9a95-3517dfb9c552 False False DCat Flighting Prod
855e8a7c-ecb4-4ca3-b045-1dfa50104289 False False Windows Store (DCat Prod)
3da21691-e39d-4da6-8a4b-b43877bcb1b7 True True Windows Server Update Service
9482f4b4-e343-43b6-b170-9a65bc822c77 False False Windows Update

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

Теперь можете выполнить сканирование на Microsoft Update. Как вы видите, в данном случае были найдены дополнительные обновления для Microsoft Visual C++ 2008 и Microsoft Silverlight.

Get-WUlist получить обновления из каталого Microsoft, а не Windows

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

Get-WUApiVersion

ComputerName PSWindowsUpdate PSWUModuleDll ApiVersion WuapiDllVersion
------------ --------------- ------------- ---------- ---------------
FS01 2.2.0.2 2.2.0.2 8.0 10.0.19041.1320

Get-WUApiVersion - узнать версию агента windows update

Чтобы убрать определенные продукты или конкретные KB из списка обновлений, которые получает ваш компьютер, вы их можете исключить по:

  • Категории (-NotCategory);
  • Названию (-NotTitle);
  • Номеру обновления (-NotKBArticleID).

Например, исключим из списка обновления драйверов, OneDrive и одну конкретную KB:

Get-WUlist -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4533002

Установка обновлений Windows с помощью Install-WindowsUpdate

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

Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot

Ключ AcceptAll включает одобрение установки для всех пакетов, а AutoReboot разрешает автоматическую перезагрузку Windows после установки обновлений.

Также можно использовать следующе параметры:

  • IgnoreReboot – запретить автоматическую перезагрузку;
  • ScheduleReboot – задать точное время перезагрузки компьютера.

Можете сохранить историю установки обновлений в лог файл (можно использовать вместо WindowsUpdate.log).

Install-WindowsUpdate -AcceptAll -Install -AutoReboot | Out-File "c:\$(get-date -f yyyy-MM-dd)-WindowsUpdate.log" -force

Можно установить только конкретные обновления по номерам KB:

Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install

Install-WindowsUpdate установка обновлений windows с помощью powershell

В данном случае нужно подтверждать установку каждого обновления вручную.
Если вы хотите исключить некоторые обновления из списка на установку, выполните:

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

Модуль позволяет удаленно запустить установку обновлений сразу на нескольких компьютерах или серверах (на компьютерах должен присутствовать модуль PSWindowsUpdate). Это особенно удобно, так как позволяет администратору не заходить вручную на все сервера во время плановой установки обновлений. Следующая команда установит все доступные обновление на трех удаленных серверах:

ServerNames = “server1, server2, server3”
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate -AcceptAll | Out-File C:\Windows\PSWindowsUpdate.log } -RunNow -Confirm:$false -Verbose -ErrorAction Ignore

Командлет Invoke-WUJob (ранее командлет назывался Invoke-WUInstall) создаст на удаленном компьютере задание планировщика, запускаемое от SYSTEM. Можно указать точное время для установки обновлений Windows:

Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate –AcceptAll -AutoReboot | Out-File C:\Windows\PSWindowsUpdate.log } -Confirm:$false -TriggerDate (Get-Date -Hour 20 -Minute 0 -Second 0)

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

Install-WindowsUpdate -ComputerName server1 -MicrosoftUpdate -AcceptAll - IgnoreReboot -SendReport –PSWUSettings @{SmtpServer="smtp.winitpro.ru";From="[email protected]";To="[email protected]";Port=25} -Verbose

Проверить статус задания установки обновления можно с помощью Get-WUJob:

Get-WUJob -ComputerName $ServerNames

Если команда вернет пустой список, значит задача установки на всех компьютерах выполнена.

Просмотр истории установленных обновлений Windows (Get-WUHistory)

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

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

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

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

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

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

"server1","server2" | Get-WUHistory| Where-Object {$_.Title -match "KB4011634"} | Select-Object *|ft

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

Get-WURebootStatus –ComputerName WKS80JT

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

Проверьте значение атрибутов
RebootRequired
и
RebootScheduled
.

Получить дату последней установки обновлений на всех компьютерах в домене можно с помощью командлета Get-ADComputer из модуля AD PowerShell:

$Computers=Get-ADComputer -Filter {enabled -eq "true" -and OperatingSystem -Like '*Windows*' }
Foreach ($Computer in $Computers)
{
Get-WULastResults -ComputerName $Computer.Name|select ComputerName, LastSearchSuccessDate, LastInstallationSuccessDate
}

По аналогии можно найти компьютеры, которые не устаналивали обновления более 40 дней и вывести результат в графическую таблицу Out-GridView:

$result=@()
Foreach ($Computer in $Computers) {
$result+= Get-WULastResults -ComputerName $Computer.Name
}
$result| Where-Object { $_.LastInstallationSuccessDate -lt ((Get-Date).AddDays(-30)) }| Out-GridView

Удаление обновлений в Windows с помощью Remove-WindowsUpdate

Для корректного удаления обновлений используется командлет Remove-WindowsUpdate. Вам достаточно указать номер KB в качестве аргумента параметра KBArticleID. Чтобы отложить автоматическую перезагрузку компьютера можно добавить ключ
–NoRestart
:

Remove-WindowsUpdate -KBArticleID KB4011634 -NoRestart

Как скрыть ненужные обновления Windows с помощью PowerShell (Hide-WindowsUpdate)?

Вы можете скрыть определенные обновления, чтобы они никогда не устанавливались службой обновлений Windows Update на вашем компьютер (чаще всего скрывают обновления драйверов). Например, чтобы скрыть обновления KB2538243 и KB4524570, выполните такие команды:

$HideList = "KB2538243", "KB4524570"
Get-WindowsUpdate -KBArticleID $HideList -Hide

или используйте alias:

Hide-WindowsUpdate -KBArticleID $HideList -Verbose

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

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

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

Get-WindowsUpdate –IsHidden

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

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

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

Get-WindowsUpdate -KBArticleID $HideList -WithHidden -Hide:$false

или так:

Show-WindowsUpdate -KBArticleID $HideList

Для тех, кто себя некомфортно чувствует в консоли PowerShell, для управления обновлениями Windows 10 могу порекомендовать графическую утилиту Windows Update MiniTool.

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.

Delete SoftwareDistribution

Delete SoftwareDistribution

Windows 10 force update using PowerShell


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

Run Windows 10 Powershell as admin

Run Windows 10 Powershell as admin
  1. 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

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

    Powershell Script running error

    Powershell Script running error
  1. 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
    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

    allow local scripts on Powershell windows 10

    Now close the PowerShell and run again as admin. After that use the command: Get-Windowsupdate

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

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 “PSWindowsUpdate” on PowerShell.

PSWindowsUpdate is a community module by Michal Gajda, available through the PowerShell Gallery. It includes the components to make it easy to check, download, and install quality updates on Windows 10.

In this guide, you’ll learn 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 download and install on your computer.

Manage updates with PowerShell

The PSWindowsUpdate module includes many options that you can use to manage updates. You can always use the Get-Command –Module PSWindowsUpdate command to query a list of the available commands.

For example, the following steps will download, install, and then reboot the computer to complete the update process:

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

Install 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 'KB5021233'

    In the command, replace “KB5021233” 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 KB5021233 on your device.

Windows 10 comes with the Windows Update Provider, but it has limited options compared to the PSWindowsUpdate module, and it’s more complicated to use.

We may earn commission for purchases using our links to help keep offering the free content. Privacy policy info.

All content on this site is provided with no warranties, express or implied. Use any information at your own risk. Always backup of your device and files before making any changes. Privacy policy info.

Начиная с версии 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 process to install Windows Updates can be a pain. Managing WSUS servers can be a headache too. However, with PowerShell, a special module, and some automation, we can schedule and automate the installation process of Windows Updates. Let’s look at PSWindowsupdate automated Windows Updates with PowerShell and see how it can come to the rescue for keeping your Windows environment up-to-date.

Table of contents

  • What is PSWindowsUpdate?
  • Why is Installing Windows Updates Important?
  • Installing the PSWindowsUpdate Module
  • Importing the PSWindowsUpdate Module
  • Checking for Available Updates
  • Downloading Windows Updates
  • Installing Windows Updates
  • Managing Windows Update History
  • Customizing Update Installation with an XML File
  • Scheduling Updates with Task Scheduler
  • Installing Specific Updates
  • Installing Only Security Updates
  • Hiding Specific Updates
  • Checking if a Reboot is Required
  • Automate Windows Updates using PSWindowsUpdate
  • PSWindowsupdate Frequently Asked Questions
  • Using Automation in the home lab
  • Wrapping up
  • Other posts you may like

What is PSWindowsUpdate?

PSWindowsUpdate is a PowerShell third-party module found in the PowerShell gallery repository available for download designed to help administrators manage Windows updates and install updates flexibly and precisely.

Unlike the standard Windows Update Service Manager (WSUS) interface, the PSWindowsUpdate module provides commands for downloading, installing, and managing updates in an automated way. However, it can work in conjunction with WSUS or pull updates directly from Microsoft.

Admins can control every aspect of Windows updates with this module – from viewing available updates and initiating installations to setting update schedules. It includes advanced features like installing specific updates, managing hidden updates, or even automating the entire update process using the Windows Task Scheduler.

Altaro VM Backup

Why is Installing Windows Updates Important?

Before diving into the PSWindowsupdate module, why is installing Windows updates important? Installing Windows updates is essential to maintaining a secure and stable system. These updates often contain security patches that protect your systems from vulnerabilities and threats. By regularly installing these updates, you’re ensuring your system’s defenses are up-to-date.

Updates also introduce new features, improve system stability, and fix existing system and software bugs. This can lead to better performance, fewer errors, and a smoother overall user experience. As such, regular updates can go a long way in minimizing downtime and reducing the need for troubleshooting.

If you are a system administrator, it may seem like a headache to patch systems constantly. However, you will thank yourself later for having a fully patched system when the next ransomware variant takes advantage of known patched vulnerabilities. Also, if you are looking at introducing any new integration or software into the environment, it is always best practice to be on the latest version of Windows, patches installed, etc.

Installing the PSWindowsUpdate Module

The installation process for the PSWindowsUpdate module starts with the command line in your PowerShell console. You need to install the module from the PowerShell gallery by typing:

Install-Module -Name PSWindowsUpdate

This command will download and install the module on your local system. However, it’s critical to note that you may need administrator privileges to install modules. Open the PowerShell prompt as an admin and run the command.

You will be prompted to trust the untrusted repository, which is normal.

Installing the PSWindowsupdate PowerShell module
Installing the PSWindowsupdate PowerShell module

Type “Y” to trust the PSGallery repository.

Accept the untrusted repository to install the module
Accept the untrusted repository to install the module

Importing the PSWindowsUpdate Module

Once installed, you need to import the module PSWindowsUpdate to begin using it. Use the following command:

Import-Module -Name PSWindowsUpdate

It loads the module into your active PowerShell session, making the related cmdlets available for use.

Importing the module in PowerShell
Importing the module in PowerShell

Checking for Available Updates

Upon successful import of the PSWindowsUpdate module, you can quickly check for available updates using the command:

Get-WindowsUpdate

This command will query your machine’s Windows Update Client settings and connect to the Microsoft Update servers to fetch the list of all available updates. You can see critical updates, security updates, and all other types of updates that your system can download and install.

Using the Get WindowsUpdate to see available updates
Using the Get WindowsUpdate to see available updates

Downloading Windows Updates

The PSWindowsUpdate module offers the command:

Download-WindowsUpdate

Use this to download Windows updates. Depending on your settings, this command initiates the download process for all approved updates from the Windows Server Update Service (WSUS) or Microsoft Update.

Download Windows Update with PowerShell
Download Windows Update with PowerShell

Installing Windows Updates

With the updates downloaded, you can install them using the ‘Install-WindowsUpdate‘ command. This command installs all downloaded updates, following which your system might need to reboot.

Install-WindowsUpdate
Running the Install WindowsUpdate command
Running the Install WindowsUpdate command

Managing Windows Update History

The PSWindowsUpdate module provides an opportunity to access your system’s update history. You can use the ‘Get-WUHistory‘ command to get a detailed log of all installed updates.

Get-WUHistory

This command returns a detailed list, including the KB number, update title, and the status of the installed updates.

Get the reboot status of your Windows Server
Get the reboot status of your Windows Server

Customizing Update Installation with an XML File

Advanced users might appreciate the ability to customize update installations using XML files. These files can specify category names to include or exclude from the update process. You can also use them to specify whether to include or exclude updates marked for automatic installation.

Scheduling Updates with Task Scheduler

In many environments, you may want to run the PSWindowsupdate command in an automated way. One way you can do this is by leveraging the power of the Windows Task Scheduler in conjunction with the PSWindowsUpdate module.

Using this combination, you can automate the download and install process at specific intervals, ensuring your system stays updated without manual intervention. We will take a look below at a script you can schedule with the Task Manager to run on a regular interval.

Installing Specific Updates

You can install specific updates using their unique KB number with the Install-WindowsUpdate command. For example, suppose you only want to install the update with the KB number KB4012606, you can do so with the following command:

Install-WindowsUpdate -KBArticleID KB4012606 -AcceptAll -AutoReboot

This command will only install the specified update and perform an automatic reboot if necessary.

Installing Only Security Updates

If you wish only to install security updates, you can do so with the following command:

Get-WindowsUpdate -Category 'SecurityUpdates' | Install-WindowsUpdate

This command first fetches only the security updates and then pipes them into the Install-WindowsUpdate command, installing only the security updates.

Hiding Specific Updates

There may be times when you want to hide a problematic update. If you want to hide Windows updates, maybe because it’s causing issues on your system, you can do so with the Hide-WindowsUpdate command. Suppose you want to hide the update with the KB number KB4012606, you can do so with the following command:

Hide-WindowsUpdate -KBArticleID KB4012606

This command will hide the specified update, preventing it from appearing in future searches for updates.

Checking if a Reboot is Required

You may want to see if there is a pending reboot required. If you want to check if a reboot is required after installing updates, you can do so with the Get-WURebootStatus command like so:

Get-WURebootStatus

This command will check and let you know if any installed updates require a reboot.

In the example, replace the placeholder KB numbers in the commands with the actual KB number of the update you’re interested in. Also, always ensure to run these commands in a safe and controlled environment, particularly when executing them on production systems or remote computers.

Get Windows Update history using PSWindowsupdate

Get Windows Update history using PSWindowsupdate

Automate Windows Updates using PSWindowsUpdate

Automation is one of the powerful features of PowerShell and by extension, the PSWindowsUpdate module. In this section, we’ll cover an example of how to write a script for automating Windows updates using PSWindowsUpdate.

# Import the PSWindowsUpdate module
Import-Module PSWindowsUpdate

# Get all available updates
$updates = Get-WindowsUpdate -MicrosoftUpdate

# Filter out optional updates
$importantUpdates = $updates | Where-Object {$_.IsDownloaded -eq $true -and $_.IsMandatory -eq $true}

# Install important updates
$importantUpdates | Install-WindowsUpdate -AcceptAll -AutoReboot

In this script, we first import the PSWindowsUpdate module. We then fetch all available updates using Get-WindowsUpdate. Using Where-Object, we filter out only the important (mandatory and already downloaded) updates, ignoring the optional ones. Lastly, we install these important updates using Install-WindowsUpdate, automatically accepting EULAs and rebooting if necessary.

You can automate the execution of this script using Task Scheduler. Here’s a basic example of how you can do this:

  1. Open Task Scheduler and create a new task.

  2. In the Triggers tab, set the schedule for the task according to your needs (for example, daily at 3 AM).

  3. In the Actions tab, select ‘Start a program’ and input powershell.exe as the program.

  4. In the ‘Add arguments’ field, input -ExecutionPolicy Bypass -File “c:your script file path.ps1” where <your script file path> is the path to your PowerShell script.

  5. Finish the wizard and the task will be scheduled.

Remember to replace the path to the script with the actual path of your script file. The system will automatically execute the update script at the specified time.

This script and scheduling are basic examples. You may need to modify the script and task parameters according to your specific requirements, such as filtering updates based on criteria or sending a report by email after installation.

Also, be sure to test these scripts in a safe and controlled environment before deploying them in production, especially when executing them on remote computers.

PSWindowsupdate Frequently Asked Questions

Can I use the PSWindowsUpdate module to manage updates on remote computers?

Using the PSWindowsUpdate module, you can manage updates both locally and on remote computers. You must ensure you have all the necessary permissions as you would normally to administer and manage a remote machine.

Can I automate the update process using the PSWindowsUpdate module?

One of the strong suits of the PSWindowsUpdate module is the ability you have to automate the process of applying Windows Updates. You can easily create a simple PowerShell script to download and install Windows Updates. It can also apply various logic such as hiding updates, downloading only certain types of updates, etc. Using Task Scheduler, it is easy to have a way to trigger the automation of PSWindowsUpdate.

How do I view hidden updates using PSWindowsUpdate?

You can use the Get-WUHiddenUpdate command to view all hidden updates on your system. If you wish to unhide an update, use the UnHide-WindowsUpdate command with the appropriate KB number.

How can I install specific categories of updates using the PSWindowsUpdate module?

You can filter updates based on a particular category using PSWindowsUpdate. It is common to see administrators only install the “security updates” available for an operating system. You can easily accomplish this with the following command:

Get-WindowsUpdate -Category 'SecurityUpdates' | Install-WindowsUpdate.

Using Automation in the home lab

Home lab automation including PowerShell

Wrapping up

The PSWindowsUpdate module is a great way for system administrators to manage single or multiple Windows servers using a fully automated solution built on top of PowerShell. It provides many capabilities that give you full control over the Windows Update service. You can use it to review available updates, download approved updates, or manage the update history. The PSWindowsupdate PowerShell module can help streamline your system’s update process, including all Windows PCs and Servers across the board.

Other posts you may like

  • Принудительное удаление обновлений windows 10
  • Проверка диска hdd windows 10
  • Пробная страница печати напечатана неправильно открыть средство устранения неполадок печати windows
  • Принудительное обновление драйверов windows 10
  • Проверка включения компьютера windows 10