Удаленный запуск обновления windows 10

Вы можете использовать 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.

Special PowerShell script PSWindowsUpdate is a great way to run Windows updates remotely from the command line on a separate computer. The PSWindowsUpdate module is not built into Windows and it is a third-party module available in the Technet Script Gallery. PSWindowsUpdate allows administrators to remotely check for updates on computers and workstations, install, remove and hide certain updates. The PSWindowsUpdate module is especially valuable when used to manage Windows updates in the Core editions of Windows Server, which do not have a graphical interface, as well as when setting up a Windows image in audit mode.

In this article, we will use Powershell for patch management. I will show a Powershell script to install Windows updates remotely also you will find another module that helps to get a list of all the missing Windows updates, as well quick guide on how to push Windows updates remotely on multiple computers using Action1 security patch management feature.

Using Builtin Tools:

1. Installing the Update Management Module PsWindowsUpdate

If you have Windows 10 installed, you can install the PSWindowsUpdate module from the online repository via the Package Manager PackageManagement with just one command:

Install-Module -Name PSWindowsUpdate

If you have an older version of Windows (Windows 7 / 8.1 / Windows Server 2008 R2 / 2012 R2) or do not have direct Internet access, you can install the PSWindowsUpdate module manually.

This module can be installed on any supported version of Windows, starting with Vista / Windows Server 2008 with PowerShell 2.0 installed (but PoSh 3.0 and higher is recommended).

  • Download the latest version of the PSWindowsUpdate module from the page: https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc and unlock the downloaded file.

1Note. In Windows 7 / Server 2008 R2, when importing a PSWindowsUpdate module, you may encounter an error like the following: The name “Unblock-File” is not recognized as the name of the cmdlet. The point is that the module uses some functions that appeared only in PowerShell 3.0. To use these functions, you will have to update PowerShell, or manually remove the line | Unblock-File from the PSWindowsUpdate.psm1 file. If you installed the Windows Update Management Module on your computer, you can install it remotely on other computers and / or servers. Use this script to copy the module to the two specified remote servers:

$Targets = "PC1-name", "PC2-name"

Invoke-Command ($Targets) {
If ($null -eq (Get-Module -Name PSWindowsUpdate -ListAvailable) ) {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module PSWindowsUpdate -Force
Import-Module PSWindowsUpdate
}
}

2. Overview Module PSWindowsUpdate Commands

The list of available cmdlets for the module can be displayed as:

get-command-module PSWindowsUpdate

Briefly describe the purpose of the module commands:

Get-WindowsUpdate an alias for Get-WUList.

Hide-WindowsUpdate alias for Hide-WUUpdate.

Install-WindowsUpdate alias for Get-WUInstall.

Uninstall-WindowsUpdate alias for Get-WUUninstall.

Add-WUOfflineSync the function allows you to install updates from the local cache using the file wsusscan.cab or wsusscn2.cab.

Add-WUServiceManager register the update server on a computer.

Get-WUHistory displays a list of installed updates.

Get-WUInstall is the main cmdlet of the PSWindowsUpdate module. Allows you to download and install updates from the server WSUS or Microsoft Update. Allows you to select categories of updates, specific updates and specify the rules for restarting the computer when installing updates.

Get-WUInstallerStatus check the status of the Windows Installer service.

Get-WURebootStatus allows you to check whether a reboot is necessary to apply a specific update.

Get-WUList lists the updates that meet the specified criteria, allows you to find and install the desired update.

Get-WUServiceManager check for update sources.

Get-WUUninstall cmdlet allows you to remove a specific update by KB ID.

Hide-WUUpdate allows you to hide certain updates from the installation.

Invoke-WUInstall manage remote installation of updates.

Remove-WUOfflineSync remove offline scan source.

Remove-WUServiceManager remove update server.

3. Get a List of Available Updates for the Computer

List the available updates for your computer on the update server:

Get-WUInstall -ListOnly

To check the list of available updates on a remote computer, run:

Get-WUList –ComputerName server2

You can check where your Windows should get updates from. Run the command:

Get-WUServiceManager

ServiceID IsManaged IsDefault Name

As you can see, the computer is configured to receive updates from the local WSUS and Windows Update service. If you want to scan your computer on Microsoft Update servers (besides Windows updates, these servers contain Office updates and other products) on the Internet, run the following command:

Get-WUinstall -MicrosoftUpdate –ListOnly

You get a warning:

Can’t find registered service Microsoft Update. Use Get-WUServiceManager to get registered service.

To enable scanning on Microsoft Update, run the following command:

Add-WUServiceManager -ServiceID “7971f918-a847-4430-9279-4a52d1efe18d” -AddServiceFlag 7

Now you can perform a scan on Microsoft Update.

To remove certain products or specific packages from the list of updates your computer receives, you can exclude them by:

  • Categories (-NotCategory);
  • Name (-NotTitle);
  • Update number (-NotKBArticleID).

For example, exclude from the list of updates for drivers, OneDrive, and one specific KB:

Get-WUInstall -NotCategory “Drivers” -NotTitle OneDrive -NotKBArticleID KB4011670 -ListOnly

4. Powershell Script to Install Windows Updates Remotely PsWindowsUpdate

To automatically download and install all available updates for your operating system, run:

Get-WUInstall -AcceptAll –IgnoreReboot

The AcceptAll key includes installation approval for all packages, and IgnoreReboot suppresses automatic restarts of Windows after installing updates.

You can install only specific update packages:

Get-WUInstall -KBArticleID KB4011670,KB4456655 –AcceptAll

If you want to remove some updates from the installation list, run:

Get-WUInstall -NotCategory “Drivers” -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll -IgnoreReboot

To automate the installation of updates with exceptions on multiple computers, you can use the following script:

PowerShell -ExecutionPolicy RemoteSigned -Command Import-Module PSWindowsUpdate; Get-WUInstall -NotCategory “Language packs” -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll –IgnoreReboot

The module allows you to remotely start the installation of updates on several computers at once or on a server (the PSWindowsUpdate module should be present on the computers). This is especially convenient, as it allows the administrator not to go manually to all servers during the scheduled installation of updates. The following command will install all available updates on three remote servers:

Invoke-WUInstall -ComputerName server1, server2, server1-Script {ipmo PSWindowsUpdate; Get-WUInstall -AcceptAll -AutoReboot | Out-File C:\Windows\PSWindowsUpdate.log } -Confirm:$false -Verbose -SkipModuleTest –RunNow

5. View the History of Installed Updates

Using the Get-WUHistory command, you can get a list of updates installed on your computer earlier. You can get information about the date of installation of a specific update:

Get-WUHistory| Where-Object {$_.Title -match “KB4011*”} | Select-Object *|ft

To obtain information about the presence of an installed update on several remote computers, you can use the following code:

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

6. The Next Feature Is Uninstalling Updates

To remove updates, use the Remove-WindowsUpdate cmdlet. You only need to specify the KB number as an argument to the KBArticleID parameter. To postpone the automatic restart of the computer, you can add the –NoRestart key:

Remove-WindowsUpdate -KBArticleID KB4011634 -NoRestart

7. How to Hide Unnecessary Updates Using Powershell

You can hide certain updates so that they are never installed by Windows Update on your computer. For example, to hide the KB4011670 and KB4456655 updates, run the following commands:

$HideList = “KB4011670”, “KB4456655”

Hide-WindowsUpdate -KBArticleID $HideList –Hide

The next time you scan for updates using the Get-WUInstall –ListOnly command, hidden updates will not be displayed in the list of patches available for installation.

You can list the updates that are hidden on this computer as follows:

Get-WindowsUpdate -IsHidden

To remove updates from hidden, run:

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

8. Additionally: As a Bonus Use Script for Getting a List of All the Missing Windows Updates

Unlock the full code below:

Install Windows Updates Using Action1:

Step 1: Sign-up for Free

Step 2: Enter AD Domain in Discovery Settings

Step 3: See All Managed Computers

Action1 will automatically find all domain computers and show them in the list of managed endpoints:

Step 4: Review Available and Missing Updates

Navigate to Patch Management to see the entire list of all patches and updates available for all computers on your entire network. To ease your work, Action1 combines all types of updates, including both Window updates and 3rd party updates (such as Google Chrome, Dropbox etc), into one uniform view.

Step 5: Option 1 Install Missing Updates Immediately or Later

Select one or more computers to update and click Deploy Update in the list of actions. You will then be prompted to deploy immediately or schedule at a later time.

Step 6: Option 2 Approve Updates for Deployment

For more streamlined workflow, you can approve updates for deployment at pre-configured maintenance windows, such as over the weekend or during non-business hours, to avoid disrupting your users.

Consider Using Action1 to Install Windows Updates Remotely if:

  • You need to run Windows updates remotely.
  • You wish to identify missing patches within your endpoint network.
  • You require tools for 3rd party software patch management.
  • You need to patch Windows servers.
  • You need to automate patch management in your organization to speed up IT task delivery.
  • You need to test and approve patches centrally and remotely.

A great many users are confused about how to install Windows updates with PowerShell. If you are also trying to figure it out, this post from MiniTool is worth reading. It explains the PSWindowsUpdate and PowerShell Windows update install in detail.

PowerShell is a powerful graphical user interface that can access various services of an operating system as an administrator via command lines. This tool can be used to deal with many different works such as copy file PowerShell, connect to exchange online, shut down/restart a remote computer, and Windows update PowerShell.

When it comes to installing Windows update on Windows 10/11/8/7, most of us may want to use the Windows Update Settings feature. Sometimes, however, the Windows Updates may be stuck at downloading or some error codes.

If you want to run a custom script to automate the installation or patch a new installation, you can perform the PowerShell Windows update cmdlets with PSWindowsUpdate. How to install/manage Windows update PowerShell on Windows 10/11? Let’s keep reading.

What Is PSWindowsUpdate

When it comes to PowerShell Windows update install and management, it’s inevitable to discuss the PSWindowsUpdate module. It is an important module that can help you install or manage Windows updates from the PowerShell command lines.

In addition, it allows an administrator to remotely check, install, hide, and remove Windows updates using PowerShell on Windows servers and workstations. It is a community module by Michal Gajda and available for installation from the PowerShell Gallery repository. So, it is not built into Windows.

How to Install/Manage Windows Updates with PowerShell

In this part, you will learn how to install Windows updates PowerShell on Windows 10/11. Besides, it also introduces other useful information related to PowerShell Windows updates, including PSWindowsUpdate install, PowerShell check for Windows updates, PowerShell Windows updates remove, etc. Let’s start exploring.

# 1. Install the PSWindowsUpdate Module

As discussed above, the PSWindowsUpdate module is necessary to make PowerShell install Windows updates. Since it is not built into Windows, you need to install it from the PowerShell Gallery. Here you can install it on Windows 10/11 and Windows Server 2022/2019/2016 via the PowerShell PackageManagement. For that:

Step 1. Right-click the Windows menu at the left button of your screen and select Windows PowerShell (Admin), and click on Yes to confirm it.

Step 2. In the elevated PowerShell window, type the following command and hit Enter to start installing PSWindowsUpdate.

Tips:

Installing the thSWindowsUpdate module requires to use the TLS 1.2 protocol for connection. To enable it for PowerShell, you can run the [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 command.

Install-Module -Name PSWindowsUpdate -Force

install PSWindowsUpdate

Step 3. Once installed, run the following command to check the package.

Get-Package -Name PSWindowsUpdate

check the PSWindowsUpdate package

Step 4. You can run the following command to show the list of available command lines in the PSWindowsUpdate module.

get-command -module PSWindowsUpdate

# 2. List All Available Windows Updates with PowerShell

Before you PowerShell install Windows updates, you can check all available Windows updates for your current computer by running the Get-WindowsUpdate or Get-WUList command in the elevated PowerShell window.

list available Windows updates using PowerShell

If you want to list all available updates on a remote computer, you can run Get-WUList –ComputerName server2 command.

# 3. Install All Available Windows Updates with PowerShell

Now, you can automatically download and install all available Windows updates PowerShell from the Windows Update servers. To do this work, open the elevated PowerShell window as we explain above and run the following command.

Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot

or

Get-WindowsUpdate -AcceptAll -Install -AutoReboot

After running the command, Windows 10/11 should download and install Windows Updates and automatically reboot the computer to apply these changes.

PowerShell install Windows update

# 4. Install Specific Windows Updates with PowerShell

Sometimes, you may want to install specific Windows updates instead of all of them. In this case, you can open the elevated PowerShell window, type the following command, hit Enter, type A, and hit Enter.

Note:

Here you need to replace KB5017308 with the KB name of the update you want to install.

Get-WindowsUpdate -Install -KBArticleID KB5017308

install specific Windows update with PowerShell

# 5. Check the Windows Updates Installed History with PowerShell

You may want to check the Windows update history with PowerShell. To do so, you can open the PowerShell window and run the Get-WUHistory command. Then you will get a list of Windows updates you installed on the computer earlier.

check Windows updates installed history with PowerShell

# 6. Remove Specific Windows Updates with PowerShell

Sometimes you may want to remove recently installed Windows updates due to some reasons such as Windows 10 keeps instilling the same updates over and over. In this case, you can run the following command and just specify the KB number as the one you want to remove from Windows 10/11.

Remove-WindowsUpdate -KBArticleID KB5017308 -NoRestart

Also, you can hide a specific Windows update so that it will be never installed by the Windows Update server on your computer. For example, you can run the following commands to hide the KB5017308 update.

  • $HideList = “KB5017308”
  • Get-WindowsUpdate -KBArticleID $HideList –Hide

hide a specific update with PowerShell

If you want to unhide the update later, you can run the following command:

Show-WindowsUpdate -KBArticleID $HideList

Further readingIf you can’t install the Windows Updates with PowerShell due to insufficient disk space, don’t worry. MiniTool Partition Wizard can help you fix the problem easily by analyzing disk space, extending partition, upgrading to a larger hard drive, etc.

If you go check the PowerShell Gallery you will find a great module in the top 100 downloads called PSWindowsUpdate. This is one of my favorite modules because it fits a specific need that many organizations have, which is orchestrating the deployment of Windows updates. There are many great cmdlets in this module, but the one I will focus on today is Invoke-WUInstall, used to install Windows updates remotely.

Contents

  1. Installing PSWindowsUpdate
  2. How Invoke-WUInstall works
  3. Install updates on multiple machines
  4. Finding errors
  5. Conclusion
  • Author
  • Recent Posts

Dan Franciscus is a systems engineer and VMware Certified Professional (VCP) specializing in VMware, PowerShell, and other Microsoft-based technologies. You can reach Dan at his blog or his Twitter at @dan_franciscus.

Installing PSWindowsUpdate

Since PSWindowsUpdate is not installed on Windows by default, we have to first install the module. Luckily, we can do this easily from the PowerShell Gallery. Note I am using an older version from July 2017 (1.5.2.6).

PS C:\WINDOWS\system32> Install-Module PSWindowsUpdate -MaximumVersion 1.5.2.6

If we run Get-Command we can see all of the commands in the PSWindowsUpdate module:

PS C:\WINDOWS\system32> Get-Command -Module PSWindowsUpdate

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           Get-WindowsUpdate                                  1.5.2.6    pswindowsupdate
Alias           Hide-WindowsUpdate                                 1.5.2.6    pswindowsupdate
Alias           Install-WindowsUpdate                              1.5.2.6    pswindowsupdate
Alias           Uninstall-WindowsUpdate                            1.5.2.6    pswindowsupdate
Function        Add-WUOfflineSync                                  1.5.2.6    pswindowsupdate
Function        Add-WUServiceManager                               1.5.2.6    pswindowsupdate
Function        Get-WUHistory                                      1.5.2.6    pswindowsupdate
Function        Get-WUInstall                                      1.5.2.6    pswindowsupdate
Function        Get-WUInstallerStatus                              1.5.2.6    pswindowsupdate
Function        Get-WUList                                         1.5.2.6    pswindowsupdate
Function        Get-WURebootStatus                                 1.5.2.6    pswindowsupdate
Function        Get-WUServiceManager                               1.5.2.6    pswindowsupdate
Function        Get-WUUninstall                                    1.5.2.6    pswindowsupdate
Function        Hide-WUUpdate                                      1.5.2.6    pswindowsupdate
Function        Invoke-WUInstall                                   1.5.2.6    pswindowsupdate
Function        Remove-WUOfflineSync                               1.5.2.6    pswindowsupdate
Function        Remove-WUServiceManager                            1.5.2.6    pswindowsupdate

How Invoke-WUInstall works

One different aspect of using Invoke-WUInstall is that it does not use traditional PowerShell remoting methods to perform Windows update installs. When you look at the source code, it actually creates and immediately runs a scheduled task on the remote machine under the SYSTEM account.

Write-Verbose "Create schedule service object"
$Scheduler = New-Object -ComObject Schedule.Service
			
$Task = $Scheduler.NewTask(0)
$RegistrationInfo = $Task.RegistrationInfo
$RegistrationInfo.Description = $TaskName
$RegistrationInfo.Author = $User.Name
$Settings = $Task.Settings
$Settings.Enabled = $True
$Settings.StartWhenAvailable = $True
$Settings.Hidden = $False
$Action = $Task.Actions.Create(0)
$Action.Path = "powershell"
$Action.Arguments = "-Command $Script"
		
$Task.Principal.RunLevel = 1

A typical use of Invoke-WUInstall would be:

Invoke-WUInstall -ComputerName Test-1 -Script {ipmo PSWindowsUpdate; Get-WUInstall -AcceptAll | Out-File C:\PSWindowsUpdate.log }
-Confirm:$false –Verbose

In this command we see Get-WUInstall, which is the command PSWindowsUpdate uses to install updates, usually from your Windows Server Update Services (WSUS) server. Get-WUInstall simply uses a COM object for Windows updates to perform the tasks needed. Notice also the use of the -AcceptAll parameter, which means it will automatically accept any updates to install.

One nice feature of Invoke-WUInstall is that it actually installs the PSWindowsUpdate module on the remote machine (if it isn’t there already). This is great when you are using the module on a new machine, or when you decide to use it for the first time.

C:\ > $cim = New-CimSession -ComputerName Test-1
C:\ > $cim

Id           : 2
Name         : CimSession2
InstanceId   : afa8c63d-fb1f-46f9-8082-c66238750a92
ComputerName : Test-1
Protocol     : WSMAN

C:\Scripts\PowerShell> (Get-ScheduledTask -TaskPath "\" -CimSession $cim -TaskName PSWindowsUpdate).actions
Id               :
Arguments        : -Command ipmo PSWindowsUpdate; Get-WUInstall  -AcceptAll -AutoReboot | Out-File C:\PSWindowsUpdate.log
Execute          : powershell
WorkingDirectory :
PSComputerName   : Test-1

As you can see, the scheduled task is going to run ipmo PSWindowsUpdate; Get-WUInstall  -AcceptAll -AutoReboot  | Out-File C:\PSWindowsUpdate.log. Using Out-File will ensure the logs of downloading and installing updates are visible so we can check against them later.

Install updates on multiple machines

The true power of Invoke-WUInstall is when you have to install updates on many machines at once. This is very easy to do, all you need is to add machines to the ‑ComputerName parameter, which then processes them in a loop (not in parallel unfortunately).

C:\ > Invoke-WUInstall -ComputerName Test-1,Test-2,Test-3,Test-4 -Script {ipmo PSWindowsUpdate; Get-WUInstall -AcceptAll | Out-File C:\
PSWindowsUpdate.log  } -Confirm:$false -Verbose
VERBOSE: Populating RepositorySourceLocation property for module PSWindowsUpdate.
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\1.5.2.6\PSWindowsUpdate.psm1'.
VERBOSE: Create schedule service object
VERBOSE: Performing the operation "Invoke WUInstall" on target "Test-1".

Finding errors

One great reason to output to a log on the remote machine is to confirm that no errors installing updates on these remote machines occurred. With some simple PowerShell, we can query these log files and search for failures.

Here is what a typical log looks like after using Get-WUInstall -AcceptAll | Out-File C:\ PSWindowsUpdate.log:

Invoke WUInstall log

Invoke WUInstall log

It includes the status of the update, its KB number, size, and title—all great information to have handy when installing updates.

Using Invoke-Command, Get-Item, and Select-String, we can use a quick technique to easily work through any computers used with Invoke-WUInstall and find Windows updates that failed to install:

Subscribe to 4sysops newsletter!

C:\> Invoke-Command -ComputerName Test-1,Test-2,Test-3 -ScriptBlock {
>> Get-Item C:\PSWindowsUpdate.log | Select-String -Pattern "failed" -SimpleMatch |
>> Select-Object -Property line } | Select-Object -Property Line,PSComputerName
Line                                                                            PSComputerName
----                                                                            --------------
4 Failed     KB4103712  30 MB 2018-05 Security Only Quality Update for Windo... Test-1

Conclusion

While there are other solutions for managing Windows update deployment, PSWindowsUpdate provides a Windows admin a free and very powerful tool to manage updates. With some simple PowerShell scripting, an admin can orchestrate updates across the enterprise in conjunction with WSUS as well.

avataravatar

Добрый день.

Есть ли утилиты/команды для удаленной работы с обновлениями на клиентах WSUS-а?
То есть известно по отчетам состояние — количество необходимых/установленных обновлений. Понятно, что есть одобренные обновления. Понятно, что политикой домена можно установить необходимость автоматической установки.
Но совсем для меня тайна, как не заходя по RDP (или в интерактивном режиме) и не вызывая wuapp (системное окно про поиск и установку обновлений) можно запустить по команде установку.

Помогите малоопытному, пожалуйста.


  • Вопрос задан

  • 4433 просмотра

Пригласить эксперта

wuauclt.exe /detectnow
wuauclt.exe /downloadnow
wuauclt.exe /updatenow

Из бесплатного — PowerShell Get-WUInstall:

# Requires PowerShell 5.0 or newer
# Apparently NUGET is required for the PSWINDOWSUPDATE module
Install-PackageProvider NuGet -Force
Import-PackageProvider NuGet -Force
# Apparentely PSWindowsUpdate module comes from the PSGallery and needs to be trusted
# See https://msdn.microsoft.com/en-us/powershell/gallery/psgallery/psgallery_gettingstarted
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
# Now actually do the update and reboot if necessary
Install-Module PSWindowsUpdate
Get-Command –module PSWindowsUpdate
Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false
Get-WUInstall –WindowsUpdate –AcceptAll –AutoReboot -install

источник

Но срабатывает не на всех обновлениях. Из найденных 8-ми поставил 7, а 1 хоть и видел, но поставить получилось только кнопкой в wuapp.
И отчет на wsus сам не отправляет. Отчет идет своей чередой как обычно.


  • Показать ещё
    Загружается…

10 окт. 2023, в 16:34

5000 руб./за проект

10 окт. 2023, в 16:28

200000 руб./за проект

10 окт. 2023, в 16:27

800 руб./за проект

Минуточку внимания

  • Удаленный компьютер отключил сеанс из за ошибки в протоколе лицензирования windows 10
  • Удаленный доступ к компьютеру windows к linux
  • Удаленный запуск программ windows 10
  • Удаленный доступ к компьютеру windows 10 программа
  • Удаленный доступ через windows server