Посмотреть установленные обновления windows 10 powershell

This article mtell you 3 accessible ways to get a list of installed Windows 10 updates. You can choose the most suitable way to view installed Windows updates.
  • Partition Wizard

  • Clone Disk

  • Top 3 Ways to Get a List of Installed Windows 10 Updates

By Ariel | Follow |
Last Updated January 25, 2021

How to get a list of installed Windows 10 updates? MiniTool Solution will discuss the top 3 ways to view installed Windows 10 updates easily. Each method has its own advantages. You can choose whichever that is suitable for your specific needs.

Windows Updatesis a powerful tool in Windows, users can check for updates, change the active hour and other useful features. Here, let’s see how to get a list of installed Windows 10 updates step by step.

Step 1. Input Windows Update in Cortana and select Windows Update Settings.

Input Windows Update in Cortana

Step 2. In the pop-up window, click on View installed update history. Then you can get a list of installed Windows 10 updates.

click on View installed update history

Then you will see all the updates installed in history on your Windows 10, including Feature Updates, Driver Updates, Quality Updates, and Other Updates.

the Windows 10 installed updates history

Tip: You need to go through the list of updates manually because you can’t search for a specific update by using this method.

In addition to this method, there are two simple ways about how to get a list of Windows 10 installed updates.

Using Command-Line Options

The list installed Windows 10 updates command line can be used to export the Windows 10 installed updates. Now, let’s see how to run them.

Option 1. WMIC Command to List Installed Windows Updates

Step 1. Type cmd in the search box to open a command prompt and select as administrator.

open Command Prompt as administrator

Step 2. Type wmic qfe list full command to get all information about each hotfix installed on your computer.

type wmic qfe list full

Then you can scroll up and down to view Windows 10 installed updates.

Or if the full information I not required, you can run wmic qfe list brief command.

 run wmic qfe list brief

Type wmic qfe list full /format: table command to format the output as a table so that it is easy to read and comprehend.

run wmic qfe list full /format: table

Option 2. Run Systeminfo Command

If you only want a list of knowledgebase updates numbers, then you can use the systeminfo command.

Step 1. Open command prompt window.

Step 2. Input systeminfo | find “KB” command and hit Enter button. Then you will see all Windows 10 knowledgebase updates number listed.

run systeminfo | find “KB” command

There is another easier way to export a list of installed Windows updates besides using the command line. Windows Powershell is a powerful tool that can be used to access various services an administrator in Windows.

Now, let see how to use this powerful tool to view Windows 10 installed updates.

Using Windows Powershell

The list installed Windows 10 updates Powershell also enables you to get a list of Windows installed updates. Here is how to do this.

Step 1. Type Windows Powershell in the search box and right-click it to select Run as administrator.

run Windows Powershell as administrator

Step 2. In the pop-up window, type get-hotfix command and hit the Enter button. Then all the hotfix installed files on your computer will be listed here and the installation date of each hotfix will also be shown.

input get hotfix command and hit enter

Top 3 ways to get a list of installed Windows 10 updates are told to you. Now, it’s your turn to have a try.

About The Author

Ariel

Position: Columnist

Ariel is an enthusiastic IT columnist focusing on partition management, data recovery, and Windows issues. She has helped users fix various problems like PS4 corrupted disk, unexpected store exception error, the green screen of death error, etc. If you are searching for methods to optimize your storage device and restore lost data from different storage devices, then Ariel can provide reliable solutions for these issues. 

  • Partition Wizard

  • Clone Disk

  • Top 3 Ways to Get a List of Installed Windows 10 Updates

By Ariel | Follow |
Last Updated January 25, 2021

How to get a list of installed Windows 10 updates? MiniTool Solution will discuss the top 3 ways to view installed Windows 10 updates easily. Each method has its own advantages. You can choose whichever that is suitable for your specific needs.

Windows Updatesis a powerful tool in Windows, users can check for updates, change the active hour and other useful features. Here, let’s see how to get a list of installed Windows 10 updates step by step.

Step 1. Input Windows Update in Cortana and select Windows Update Settings.

Input Windows Update in Cortana

Step 2. In the pop-up window, click on View installed update history. Then you can get a list of installed Windows 10 updates.

click on View installed update history

Then you will see all the updates installed in history on your Windows 10, including Feature Updates, Driver Updates, Quality Updates, and Other Updates.

the Windows 10 installed updates history

Tip: You need to go through the list of updates manually because you can’t search for a specific update by using this method.

In addition to this method, there are two simple ways about how to get a list of Windows 10 installed updates.

Using Command-Line Options

The list installed Windows 10 updates command line can be used to export the Windows 10 installed updates. Now, let’s see how to run them.

Option 1. WMIC Command to List Installed Windows Updates

Step 1. Type cmd in the search box to open a command prompt and select as administrator.

open Command Prompt as administrator

Step 2. Type wmic qfe list full command to get all information about each hotfix installed on your computer.

type wmic qfe list full

Then you can scroll up and down to view Windows 10 installed updates.

Or if the full information I not required, you can run wmic qfe list brief command.

 run wmic qfe list brief

Type wmic qfe list full /format: table command to format the output as a table so that it is easy to read and comprehend.

run wmic qfe list full /format: table

Option 2. Run Systeminfo Command

If you only want a list of knowledgebase updates numbers, then you can use the systeminfo command.

Step 1. Open command prompt window.

Step 2. Input systeminfo | find “KB” command and hit Enter button. Then you will see all Windows 10 knowledgebase updates number listed.

run systeminfo | find “KB” command

There is another easier way to export a list of installed Windows updates besides using the command line. Windows Powershell is a powerful tool that can be used to access various services an administrator in Windows.

Now, let see how to use this powerful tool to view Windows 10 installed updates.

Using Windows Powershell

The list installed Windows 10 updates Powershell also enables you to get a list of Windows installed updates. Here is how to do this.

Step 1. Type Windows Powershell in the search box and right-click it to select Run as administrator.

run Windows Powershell as administrator

Step 2. In the pop-up window, type get-hotfix command and hit the Enter button. Then all the hotfix installed files on your computer will be listed here and the installation date of each hotfix will also be shown.

input get hotfix command and hit enter

Top 3 ways to get a list of installed Windows 10 updates are told to you. Now, it’s your turn to have a try.

About The Author

Ariel

Position: Columnist

Ariel is an enthusiastic IT columnist focusing on partition management, data recovery, and Windows issues. She has helped users fix various problems like PS4 corrupted disk, unexpected store exception error, the green screen of death error, etc. If you are searching for methods to optimize your storage device and restore lost data from different storage devices, then Ariel can provide reliable solutions for these issues. 

Вы можете использовать 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%System32WindowsPowerShellv1.0Modules
    (при постоянном использовании модуля это лучший вариант);
  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 \fs01ps

Обзор команд модуля 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:localhostclientTrustedHosts -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:WindowsPSWindowsUpdate.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:WindowsPSWindowsUpdate.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:

[email protected]()
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.

Installing Windows Updates manually can be a drag. Why not automate the entire process with PowerShell? Get started controlling Windows updates with the PSWindowsUpdate module in PowerShell!

In this tutorial, you will learn how to download and install updates on your Windows machine through PowerShell.

Prerequisites

This tutorial uses Windows 10 Build 19042 for demonstrations throughout this tutorial, but older ones, such as Windows 7 and 8.1, will work.

Installing the PSWindowsUpdate Module

The PSWindowsUpdate module is a third-party module available in PowerShell Gallery that lets you manage Windows updates from the PowerShell console. The PowerShell Gallery is the central repository where you can find and share PowerShell modules.

With the PSWindowsUpdate module, you can remotely check, install, update and remove updates on Windows servers and workstations. But first, you need to install the PSWindowsUpdate module on your machine.

1. Open PowerShell as administrator.

2. Run the Install-Module command to download and install the PSWindowUpdate module from the PowerShell gallery repository. The -Force parameter tells the command to ignore prompt messages and continue installing the module.

Install-Module -Name PSWindowsUpdate -Force

If you’re on an older version of Windows, you can download the PSWindowsUpdate module manually.

3. Next, run the Import-Module command below to import the PSWindowsUpdate module to PowerShell’s current session. Once imported, you can then use the module to manage Windows updates on your machine.

You may run into an error importing the module for the first time saying “The specified module ‘PSWindowsUpdate’ was not loaded”. In that case, you must allow executing scripts on your machine.

Run the command Set-ExecutionPolicy -ExecutionPolicy RemoteSigned to enable execute remote scripts on your computer. Now try importing the PSWindowsUpdate module again.

Import-Module PSWindowsUpdate

4. Finally, run the command below to see all commands (Get-Command) available for the PSWindowsUpdate module. Some of these commands are what you will use to manage Windows updates on your machine. Get-Command -Module PSWindowsUpdate

Get-Command -Module PSWindowsUpdate

Checking for Available Windows Updates

With the PSWindowsUpdate module installed, you can now run a command to list the updates available for your computer before installing them. Checking the list of updates is a good practice to avoid installing an update you don’t need.

Run the Get-WindowsUpdate command to list all the Windows updates

Below, you can see the list of available Windows updates along with their Knowledge-Base (KB) numbers. Take note of any KB number of a Windows update that you may want to prevent installing later, perhaps one that you deem not important.

Listing Available Windows Updates
Listing Available Windows Updates

Perhaps you also want to check where Windows gets an update from to see if the source is trustworthy. If so, the Get-WUServiceManager command will do the trick.

Run the Get-WUServiceManager to show the list of available update services.

There’s no official documentation about the update the sources, but each is defined below:

  • Microsoft Update – the standard update source
  • DCat Flighting Prod – an alternative MS supdate ource for specific flighted update items (from previews, etc)
  • Windows Store (DCat Prod) – normally just Windows Store, but has Dcat Prod when for insider preview PC
  • Windows Update – an older update source for Windows Vista and older Windows OS.
Showing where Windows Gets Updates
Showing where Windows Gets Updates

Excluding Windows Updates from Installing

Now you’ve seen the Windows updates available, perhaps you prefer not to install some of them on your computer. In that case, you can choose not to install them by hiding them.

Run the Hide-WindowsUpdate command below to hide a Windows update tagged with the specified KB number (-KBArticleID KB4052623). You can specify the KB number you took note of in the “Checking for Available Windows Updates” section instead.

PowerShell will ask for your confirmation before executing the command. Confirm the command with the “A” key, then press Enter.

	Hide-WindowsUpdate -KBArticleID KB4052623
Hiding an Update Based on the Update's KB Number
Hiding an Update Based on the Update’s KB Number

If you change your mind and want to install the update in the future, you can show the update similar to how you hid the update. To show the update, run the Show-WindowsUpdate command along with the update’s KB number, like this: Show-WindowsUpdate -KBArticleID KB4052623

Installing Windows Updates

Now that you can discover and exclude some updates from installing, let’s now check out how to install them.

But before installing updates, checking if updates require a system reboot is a good practice. Why? Knowing whether the Windows updates require a reboot beforehand tells you to save all your work and complete other ongoing installations before diving to the Windows update.

Now run the Get-WURebootStatus command to determine if any of the Windows updates require a reboot. The command returns either True or False value to indicate the reboot status

Below, you can see the command returned a False value, which indicates a reboot is not required. So go nuts and install the updates you deem are necessary.

Checking if Reboot is Required After Installing Windows Updates
Checking if Reboot is Required After Installing Windows Updates

Downloading and Installing All Available Updates

If you’re not picky when it comes to updates, running the Install-WindowsUpdate command on its own lets you install all available Windows updates. But perhaps, you want to install the updates without having to accept prompts. If so, you need to add the -AcceptAll parameter as shown below.

Run the Install-WindowsUpdate command below to install all available Windows updates. The -AcceptAll parameter tells the command to suppress prompts and continue installing all updates.

If you prefer to reboot your computer once the installation is completed automatically, add the -AutoReboot parameter.

Install-WindowsUpdate -AcceptAll -AutoReboot
Installing All Windows Updates
Installing All Windows Updates

If you prefer to install selected updates only, add the -KBArticleID parameter in the Install-WindowsUpdate command, followed by the update’s KB number, like this: Install-WindowsUpdate -KBArticleID KB2267602

Checking Windows Update History

Now you have installed windows updates on your computer, but perhaps something has gone wrong during the installation. If so, you can check your update history using the Get-WUHistory command. The Get-WUHistory prints out all the installed updates to the console with their installation result.

Run the Get-WUHistory command below to check Windows update history.

Below, you can see that most of the updates have the Succeeded result status, while some have InProgress status.

Viewing Windows Update History
Viewing Windows Update History

Uninstalling Windows Updates

There are times when you install an update you don’t deem important at the moment, or there are updates you suspect of causing an issue on your system. In those times, you can properly uninstall the updates with the Remove-WindowsUpdate command.

Run the Remove-WindowsUpdate command below to uninstall a Windows update tagged with a specific KB number (-KBArticleID KB2267602).

PowerShell will require confirmation before executing the command. Press the “A” key and hit enter to confirm the command.

Remove-WindowsUpdate -KBArticleID KB2267602
Uninstalling Windows Updates
Uninstalling Windows Updates

Conclusion

Throughout this tutorial, you’ve learned about the PSWindowsUpdate Module. You’ve also gone through selectively installing and uninstalling Windows updates.

You’ve learned that you have full control over the Windows updates with PowerShell. Now, would you prefer installing updates in PowerShell over a GUI method? Perhaps learn more about building a Windows update report?

  • 14 Aug 2011 8:48 AM

    I wondering why the hotfixes report i generated show difference InstalledOn(-1 day) compare to Installed updates date i refer from Control panel?

  • 14 Aug 2011 9:13 AM

    The data in WMI is stored in UTC format. And it is not translated into your local time when you use low-level tools such as Windows PowerShell or WMIC. In contrast, the Control Panel is an end-user friendly app that does the conversion for you.

    From your profile it looks like you’re located in Singapore which means UTC+8 time zone. Effectively, if you installed something right now it would be 12 AM Aug 15 for you (as well as from the Control Panel point of view). But internally, in UTC, it would still be 4 PM Aug 14 (and this is what the WMI tools would show you).

    Does this make sense?

  • 14 Aug 2011 11:05 AM

    Yes, it is acceptable and rational, this report extraction is useful to me. Is it means that manual process needed to correct the report or we can correct it in some other way when the report is generated? By the way, how to include «name» of each update.

  • 14 Aug 2011 12:58 PM

    Well, I believe we should always start with your end goals. What do you intend to achieve? Probably, scripting is not your best friend. Basically, an end user should be happy with the Control Panel applet since it is the most convenient and friendly way, yet providing very accurate results. On the flip side, an enterprise network admin is strongly encouraged go with some more robust tool like inventory features of ConfigMgr. With that said, I hope someone (probably myself) updates this article in the near future to address more use cases.

  • 15 Aug 2011 5:36 AM

    I am handling part of process patch management to ensure another enterprise updated their patch properly and generated a report for them monthly but i don’t support their infrastructure. The powershell script work for me, thanks :-)

    I am using SCE and SCOM in company i supporting and i know it’s great tool to have.

  • 16 Oct 2012 5:40 PM

    Thank you.

  • 20 Mar 2014 1:53 PM

    Here’s an optimized script:

    $Session = New-Object -ComObject «Microsoft.Update.Session»

    $Searcher = $Session.CreateUpdateSearcher()

    $historyCount = $Searcher.GetTotalHistoryCount()

    $Searcher.QueryHistory(0, $historyCount) | Select-Object Date,

       @{name=»Operation»; expression={switch($_.operation){

           1 {«Installation»}; 2 {«Uninstallation»}; 3 {«Other»}}}},

       @{name=»Status»; expression={switch($_.resultcode){

           1 {«In Progress»}; 2 {«Succeeded»}; 3 {«Succeeded With Errors»};

           4 {«Failed»}; 5 {«Aborted»}

    }}}, Title | Export-Csv -NoType «$Env:userprofileDesktopWindows Updates.csv»

    Also if you want to run scripts on Windows 8 or 2008 R2, you’ll need to right click on PowerShell and select «Run as administrator», execute the following and answer «y» pressing enter:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

    Info from: technet.microsoft.com/…/hh847748.aspx

  • 9 Jun 2014 8:46 AM

    I used the powershell method to extract all the updates to a file but I could not find update cumulative update KB2936068. I couldn’t find «2936068» in the registry either.

    I’m running W7 Pro 32-bit with IE9. IE9 shows KB2953522 update (about IE) and I can find that KB in both the powershell output and in the registry. KB2953522 requires the cumulative update KB2936068 so KB2936068 must be installed, but why can’t I find KB2936068 on my machine?

  • 15 Sep 2014 9:12 PM

    Thanks for the $Searcher tip.  I have adapted it to find some objective detail for a controversial update.

    answers.microsoft.com/…/83352bfe-86df-4a3b-9886-24c1a9401b78

    (No links alllowed?)

  • Skip to content

    Powershell — Список установленных обновлений

    Powershell — Список установленных обновлений

    Хотите узнать, как перечислить установленные обновления с помощью Powershell? В этом учебнике мы покажем вам, как использовать Powershell, чтобы получить список установленной истории обновления на компьютере под управлением Windows.

    • Windows 2012 R2
    • Windows 2016
    • Windows 2019
    • Windows 10

    Список оборудования

    В следующем разделе представлен список оборудования, используемого для создания этого учебника.

    Как Amazon Associate, я зарабатываю от квалификационных покупок.

    Похожий учебник — PowerShell

    На этой странице мы предлагаем быстрый доступ к списку учебников, связанных с PowerShell.

    Учебник Powershell — Список установленных обновлений

    Как Администратор, запустите новый запрос командной строки POWERSHELL.

    Windows 10 - powershell elevated

    Получите список установленных обновлений на Windows.

    Получите историю установленных обновлений, организованных к дате установки.

    Отображение списка установленных обновлений, отформатированных как сетка.

    Powershell - List installed updates

    Создайте текстовый файл, содержащий список установленных обновлений.

    Создайте файл CSV, содержащий список установленных обновлений.

    Получить информацию из конкретного обновления Windows.

    Поздравляю! Вы можете отображать список установленных обновлений на Windows с помощью Powershell.

    VirtualCoin CISSP, PMP, CCNP, MCSE, LPIC22021-05-16T00:43:32-03:00

    Related Posts

    Page load link

    Join Our Newsletter 

    Stay updated with the latest tutorials

    close-link

    This website uses cookies and third party services.

    Ok

    You can use the PSWindowsUpdate PowerShell module to manage Windows updates from the command line. The PSWindowsUpdate module is not built into Windows and is available for installation from the PowerShell Gallery repository. PSWindowsUpdate allows administrators to remotely check, install, remove, and hide updates on Windows servers and workstations. The PSWindowsUpdate module is especially valuable to manage updates on Windows Server Core or Hyper-V Server (which don’t have a GUI), and when configuring a Windows image in the audit mode.

    Contents:

    • Installing the PSWindowsUpdate Module
    • PSWindowsUpdate Cmdlets List
    • Scan and Download Windows Updates with PowerShell
    • Installing Windows Updates with PowerShell (Install-WindowsUpdate)
    • Install Windows Update on Remote Computers with PowerShell
    • Check Windows Update History with PowerShell (Get-WUHistory)
    • Uninstalling Windows Updates with PowerShell (Remove-WindowsUpdate)
    • How to Hide Windows Updates with PowerShell?

    Installing the PSWindowsUpdate Module

    You can install the PSWindowsUpdate module on Windows 10/11 and Windows Server 2022/2019/2016 from the online repository (PSGallery) using the PackageManagement with a single command:

    Install-Module -Name PSWindowsUpdate -Force

    After the installation is complete, you need to check the package:

    Get-Package -Name PSWindowsUpdate

    Install-Module PSWindowsUpdate from PSGallery

    When installing the PowerShell module on earlier versions of Windows 2012R2/Windows 8.1 and below, you may receive an error:

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

    To install the module, you need to use the TLS 1.2 protocol for connection. Enable it for the current PowerShell session with the command:

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

    PowerShell Install-Module Error: Unable to Download from URI

    If you have an older Windows version (Windows 7/8.1/Windows Server 2008 R2/2012 R2) or you don’t have direct Internet access, you can install PSWindowsUpdate manually (check the guide “How to install PowerShell modules offline?”).

    1. Download the PSWindowsUpdate module to any online computer: Save-Module –Name PSWindowsUpdate –Path C:ps;
    2. Copy the module to the following folder on the target computer %WINDIR%System32WindowsPowerShellv1.0Modules;copy pswindowsupdate module to offline windows computer
    3. Configure the PowerShell script execution policy: Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force
    4. You can now import the module into your PowerShell session: Import-Module PSWindowsUpdate

    Note. In Windows 7/Windows Server 2008 R2, when importing the PSWindowsUpdate module, the following error may appear: The term “Unblock-File” is not recognized as the name of a cmdlet. The cause is that the module uses some functions that appeared only in PowerShell 3.0. To use these functions, you will have either to update the PowerShell version or delete the | Unblock-File line from the PSWindowsUpdate.psm1 file manually.

    After installing the PSWindowsUpdate module on your computer, you can remotely install it on other computers or servers using the Update-WUModule cmdlet. For example, to copy the PSWindowsUpdate module from your computer to two remote hosts, run the commands (you need access to the remote servers via the WinRM protocol):

    $Targets = "lon-fs02", "lon-db01"
    Update-WUModule -ComputerName $Targets –Local

    To save (export) the PoSh module to a shared network folder for further importing on other computers, run:

    Save-Module -Name PSWindowsUpdate –Path \lon-fs02psmodules

    PSWindowsUpdate Cmdlets List

    You can display the list of available cmdlets in the PSWindowsUpdate module as follows:

    get-command -module PSWindowsUpdate

    Let’s describe the usage of the module commands in brief:

    • Clear-WUJob – use the Get-WUJob to clear the WUJob in Task Scheduler;
    • Download-WindowsUpdate (alias for Get-WindowsUpdate –Download) — get a list of updates and download them;
    • Get-WUInstall, Install-WindowsUpdate (alias for Get-WindowsUpdate –Install) – install Windows updates;
    • Hide-WindowsUpdate (alias for Get-WindowsUpdate -Hide:$false) – hide update;
    • Uninstall-WindowsUpdate – remove update using the Remove-WindowsUpdate;
    • Add-WUServiceManager – register the update server (Windows Update Service Manager) on the computer;
    • Enable-WURemoting — enable Windows Defender firewall rules to allow remote use of the PSWindowsUpdate cmdlets;
    • Get-WindowsUpdate (Get-WUList) — displays a list of updates that match the specified criteria, allows you to find and install the updates. This is the main cmdlet of the PSWindowsUpdate module. Allows to download and install updates from a WSUS server or Microsoft Update. Allows you to select update categories, specific updates and set the rules of a computer restart when installing the updates;
    • Get-WUApiVersion – get the Windows Update Agent version on the computer;
    • Get-WUHistory – display a list of installed updates (update history);
    • Get-WUInstallerStatus — check the Windows Installer service status;
    • Get-WUJob – check for WUJob update tasks in the Task Scheduler;
    • Get-WULastResults — dates of the last search and installation of updates (LastSearchSuccessDate and LastInstallationSuccessDate);
    • Get-WURebootStatus — allows you to check whether a reboot is needed to apply a specific update;
    • Get-WUServiceManager – list update sources;
    • Get-WUSettings – get Windows Update client settings;
    • Invoke-WUJob – remotely call WUJobs task in the Task Scheduler to immediately execute PSWindowsUpdate commands;
    • Remove-WindowsUpdate – allows to uninstall an update by KB ID;
    • Remove-WUServiceManager – disable Windows Update Service Manager;
    • Set-PSWUSettings – save PSWindowsUpdate module settings to the XML file;
    • Set-WUSettings – configure Windows Update client settings;
    • Update-WUModule – update the PSWindowsUpdate module (you can update the module on a remote computer by copying it from the current one, or updating from PSGallery);
    • Reset-WUComponentsallows you to reset the Windows Update agent on the computer to the default state.

    list PSWindowsUpdate module commands

    To check the current Windows Update client settings, run the command:

    Get-WUSettings

    ComputerName                                 : WKS5S2N39S2
    WUServer                                     : http://MN-WSUS:8530
    WUStatusServer                               : http://MN-WSUS:8530
    AcceptTrustedPublisherCerts                  : 1
    ElevateNonAdmins                             : 1
    DoNotConnectToWindowsUpdateInternetLocations : 1
    TargetGroupEnabled                           : 1
    TargetGroup                                  : ServersProd
    NoAutoUpdate                                 : 0
    AUOptions                                    : 3 - Notify before installation
    ScheduledInstallDay                          : 0 - Every Day
    ScheduledInstallTime                         : 3
    UseWUServer                                  : 1
    AutoInstallMinorUpdates                      : 0
    AlwaysAutoRebootAtScheduledTime              : 0
    DetectionFrequencyEnabled                    : 1
    DetectionFrequency                         : 4
    

    In this example, the Windows Update agent on the computer is configured with a GPO to receive updates from the local WSUS server.

    The Reset-WUComponents -Verbose cmdlet allows you to reset all Windows Update Agent settings, re-register libraries, and restore the wususerv service to its default state.

    reset windows update components with powershell

    Scan and Download Windows Updates with PowerShell

    You can list the updates available for the current computer on the update server using the Get-WindowsUpdate or Get-WUList commands.

    Get-WUList - view available windows updates

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

    Get-WUList –ComputerName server2

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

    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 – get update sources

    As you can see, the computer is configured to receive updates from the local WSUS server (Windows Server Update Service = True). In this case, you should see a list of updates approved for your computer.

    If you want to scan your computer against Microsoft Update servers on the Internet (in addition to Windows updates, these servers contain Office and other Microsoft product updates), run this command:

    Get-WUlist -MicrosoftUpdate

    You will get this warning:

    Get-WUlist : Service Windows Update was not found on computer. Use Get-WUServiceManager to get registered service.

    To allow scanning on Microsoft Update, run this command:

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

    You can now scan against Microsoft Update. In this case, additional updates were found for Microsoft Visual C ++ 2008 and Microsoft Silverlight.

    get updates from Microsoft Update for additional microsoft products

    To check the version of the Windows Update Agent on the computer, run the command:

    Get-WUApiVersion

    ComputerName PSWindowsUpdate PSWUModuleDll ApiVersion WuapiDllVersion
    ------------ --------------- ------------- ---------- ---------------
    DESKTOP-J... 2.1.1.2 2.2.0.2 8.0 10.0.19041.1320

    Get-WUApiVersion - check windows update client version

    To remove specific products or KBs from the list of updates received by your computer, you can exclude them by:

    • Category (-NotCategory);
    • Title (-NotCategory);
    • Update number (-NotKBArticleID).

    For example, let’s exclude OneDrive, driver updates, and the specific KB from the list:

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

    Installing Windows Updates with PowerShell (Install-WindowsUpdate)

    To automatically download and install all available updates for your Windows device from Windows Update servers (instead of local WSUS), run the command:

    Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot

    The AcceptAll parameter accepts the installation of all update packages, and AutoReboot allows Windows to automatically restart after the updates are installed.

    You can also use the following options:

    • IgnoreReboot – disable automatic reboot;
    • ScheduleReboot – set the exact time to restart the computer.

    You can save the update installation history to a log file (you can use it instead of WindowsUpdate.log file).

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

    You can install only the specific update packages by KB numbers:

    Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install

    Get-WindowsUpdate Install updates powershell

    In this case, you need to confirm the installation of each update manually.

    If you want to exclude certain updates from the installation list, run this command:

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

    Install Windows Update on Remote Computers with PowerShell

    The PSWindowsUpdate module allows you to install updates remotely on multiple workstations or servers at once (the PSWindowsUpdate must be installed/imported on these computers). This is very convenient because the administrator doesn’t have to manually log on to remote Windows hosts to install updates. WinRM must be enabled and configured on remote computers (manually or via GPO).

    Almost all PSWindowsUpdate module cmdlets allow you to manage and install Windows updates on remote computers with the –Computername attribute.

    Install the PSWindowsUpdate module on remote computers and allow access via dynamic RPC ports to the dllhost.exe process in the Windows Defender Firewall. You can use the Invoke-Command cmdlet to configure the PSWindowsUpdate module on remote computers:

    $Targets = "lon-fs02", "lon-db01"
    Invoke-Command -ComputerName $Target -ScriptBlock {Set-ExecutionPolicy RemoteSigned -force }
    Invoke-Command -ComputerName $Target -ScriptBlock {Import-Module PSWindowsUpdate; Enable-WURemoting}

    The PSWindowsUpdate module can be used to remotely manage Windows updates both on computers in an AD domain and in a workgroup (requires PowerShell Remoting configuration for workgroup environment).

    In order to manage updates on remote computers, you need to add hostnames to your winrm trusted host list or configure PowerShell Remoting (WinRM) via HTTPS:

    winrm set winrm/config/client '@{TrustedHosts="server1,server2,…"}'

    Or with PowerShell :
    Set-Item wsman:localhostclientTrustedHosts -Value server1 -Force

    The following command will install all available updates on three remote Windows hosts:

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

    The Invoke-WUJob cmdlet (previously called Invoke-WUInstall) will create a scheduler task on the remote computer that runs under a local SYSTEM account.

    You can specify the exact time to install Windows updates:

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

    You can check the status of the update installation task using the Get-WUJob:

    Get-WUJob -ComputerName $ServerNames

    If the command returns an empty list, then the update installation task on all computers has been completed.

    You can install updates on a remote computer and send an email report to the administrator:

    Install-WindowsUpdate -ComputerName nysrv1 -MicrosoftUpdate -AcceptAll - IgnoreReboot -SendReport –PSWUSettings @{SmtpServer="smtp.woshub.com";From="update_alert@woshub.com";To="wsus_admin@woshub.com";Port=25} -Verbose

    Check Windows Update History with PowerShell (Get-WUHistory)

    Using the Get-WUHistory cmdlet, you can get the list of updates installed on a computer earlier automatically or manually.

    Get-WUHistory - checking windows update history

    You can get the information about the installation date of a specific update:

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

    Get-WUHistory for a specific KB

    To find out if the specific update has been installed on multiple remote computers, you can use this PowerShell code:

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

    Check if the computer needs to be restarted after installing the update (pending reboot):

    Get-WURebootStatus –ComputerName WKS21TJS

    check for pending reboot with powershell Get-WURebootStatus

    Check the value of the RebootRequired and RebootScheduled attributes.

    You can generate a report with the dates when updates were last installed on all computers in the domain using the Get-ADComputer cmdlet (from the Active Directory for PowerShell module):

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

    By analogy, you can find computers that have not installed updates for more than 60 days and display the result in the Out-GridView interactive table:

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

    Uninstalling Windows Updates with PowerShell (Remove-WindowsUpdate)

    You can use the Remove-WindowsUpdate cmdlet to correctly uninstall the updates with PowerShell. Just specify the KB number as an argument of the KBArticleID parameter. To delay automatic computer restart, add the –NoRestart option:

    Remove-WindowsUpdate -KBArticleID KB4489873 -NoRestart

    How to Hide Windows Updates with PowerShell?

    You can hide the specific updates so they will be never installed by the Windows Update service on your computer (most often you need to hide the driver updates). For example, to hide the KB4489873 and KB4489243 updates, run these commands:
    $HideList = "KB4489873", "KB4489243"
    Get-WindowsUpdate -KBArticleID $HideList –Hide

    powershell - hide specific KBs in windows update

    Now the next time you scan for updates using the Get-WUlist command, the hidden updates won’t be displayed in the list of updates available for installation.

    This is how you can display the list of updates hidden on this computer:

    Get-WindowsUpdate –IsHidden

    Notice that the H (Hidden) attribute has appeared in the Status column of hidden updates.

    Get-WindowsUpdate –IsHidden - find hidden updates

    To unhide some updates, run this command:

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

    or:

    Show-WindowsUpdate -KBArticleID $HideList

    For those who feel uncomfortable in the PowerShell console, I would recommend a graphic Windows Update MiniTool to manage updates in Windows 10/11 and Windows Server 2022/2019.

    Download PC Repair Tool to quickly find & fix Windows errors automatically

    Usually, users who wish to find out whether the latest cumulative update is installed on their Windows 11/10 system use this method to check the Windows Update History. In this post, we will show you how to get current patch information for Windows 11/10 using a PowerShell script.

    PowerShell script to check Windows Update status

    PowerShell script to check Windows Update status

    The PowerShell script can be used to report which OS build a Windows 11/10 computer is currently on as well as which update is the latest update available to the device. It can also report on all Windows updates published for the version of Windows 11/10 a workstation is currently on.

    When you run the script, the following information will be displayed:

    • Current OS version
    • Current OS Edition
    • Current OS Build number
    • The installed update that corresponds to that build number, as well as the KB number and a link to the info page
    • The latest available update for the OS version

    To get Windows 10 current patch information using PowerShell script, you need to create and run the PowerShell script using the code below from Github.

    [CmdletBinding()]
    Param(
    [switch]$ListAllAvailable,
    [switch]$ExcludePreview,
    [switch]$ExcludeOutofBand
    )
    $ProgressPreference = 'SilentlyContinue'
    $URI = "https://aka.ms/WindowsUpdateHistory" # Windows 10 release history
    
    Function Get-MyWindowsVersion {
    [CmdletBinding()]
    Param
    (
    $ComputerName = $env:COMPUTERNAME
    )
    
    $Table = New-Object System.Data.DataTable
    $Table.Columns.AddRange(@("ComputerName","Windows Edition","Version","OS Build"))
    $ProductName = (Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' -Name ProductName).ProductName
    Try
    {
    $Version = (Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' -Name ReleaseID -ErrorAction Stop).ReleaseID
    }
    Catch
    {
    $Version = "N/A"
    }
    $CurrentBuild = (Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' -Name CurrentBuild).CurrentBuild
    $UBR = (Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' -Name UBR).UBR
    $OSVersion = $CurrentBuild + "." + $UBR
    $TempTable = New-Object System.Data.DataTable
    $TempTable.Columns.AddRange(@("ComputerName","Windows Edition","Version","OS Build"))
    [void]$TempTable.Rows.Add($env:COMPUTERNAME,$ProductName,$Version,$OSVersion)
    
    Return $TempTable
    }
    
    Function Convert-ParsedArray {
    Param($Array)
    
    $ArrayList = New-Object System.Collections.ArrayList
    foreach ($item in $Array)
    { 
    [void]$ArrayList.Add([PSCustomObject]@{
    Update = $item.outerHTML.Split('>')[1].Replace('</a','').Replace('—',' - ')
    KB = "KB" + $item.href.Split('/')[-1]
    InfoURL = "https://support.microsoft.com" + $item.href
    OSBuild = $item.outerHTML.Split('(OS ')[1].Split()[1] # Just for sorting
    })
    }
    Return $ArrayList
    }
    
    If ($PSVersionTable.PSVersion.Major -ge 6)
    {
    $Response = Invoke-WebRequest -Uri $URI -ErrorAction Stop
    }
    else 
    {
    $Response = Invoke-WebRequest -Uri $URI -UseBasicParsing -ErrorAction Stop
    }
    
    If (!($Response.Links))
    { throw "Response was not parsed as HTML"}
    $VersionDataRaw = $Response.Links | where {$_.outerHTML -match "supLeftNavLink" -and $_.outerHTML -match "KB"}
    $CurrentWindowsVersion = Get-MyWindowsVersion -ErrorAction Stop
    
    If ($ListAllAvailable)
    {
    If ($ExcludePreview -and $ExcludeOutofBand)
    {
    $AllAvailable = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0] -and $_.outerHTML -notmatch "Preview" -and $_.outerHTML -notmatch "Out-of-band"}
    }
    ElseIf ($ExcludePreview)
    {
    $AllAvailable = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0] -and $_.outerHTML -notmatch "Preview"}
    }
    ElseIf ($ExcludeOutofBand)
    {
    $AllAvailable = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0] -and $_.outerHTML -notmatch "Out-of-band"}
    }
    Else
    {
    $AllAvailable = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0]}
    }
    $UniqueList = (Convert-ParsedArray -Array $AllAvailable) | Sort OSBuild -Descending -Unique
    $Table = New-Object System.Data.DataTable
    [void]$Table.Columns.AddRange(@('Update','KB','InfoURL'))
    foreach ($Update in $UniqueList)
    {
    [void]$Table.Rows.Add(
    $Update.Update,
    $Update.KB,
    $Update.InfoURL
    )
    }
    Return $Table
    }
    
    $CurrentPatch = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'} | Select -First 1
    If ($ExcludePreview -and $ExcludeOutofBand)
    {
    $LatestAvailablePatch = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0] -and $_.outerHTML -notmatch "Out-of-band" -and $_.outerHTML -notmatch "Preview"} | Select -First 1
    }
    ElseIf ($ExcludePreview)
    {
    $LatestAvailablePatch = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0] -and $_.outerHTML -notmatch "Preview"} | Select -First 1
    }
    ElseIf ($ExcludeOutofBand)
    {
    $LatestAvailablePatch = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0] -and $_.outerHTML -notmatch "Out-of-band"} | Select -First 1
    }
    Else
    {
    $LatestAvailablePatch = $VersionDataRaw | where {$_.outerHTML -match $CurrentWindowsVersion.'OS Build'.Split('.')[0]} | Select -First 1
    }
    
    
    $Table = New-Object System.Data.DataTable
    [void]$Table.Columns.AddRange(@('OSVersion','OSEdition','OSBuild','CurrentInstalledUpdate','CurrentInstalledUpdateKB','CurrentInstalledUpdateInfoURL','LatestAvailableUpdate','LastestAvailableUpdateKB','LastestAvailableUpdateInfoURL'))
    [void]$Table.Rows.Add(
    $CurrentWindowsVersion.Version,
    $CurrentWindowsVersion.'Windows Edition',
    $CurrentWindowsVersion.'OS Build',
    $CurrentPatch.outerHTML.Split('>')[1].Replace('</a','').Replace('—',' - '),
    "KB" + $CurrentPatch.href.Split('/')[-1],
    "https://support.microsoft.com" + $CurrentPatch.href,
    $LatestAvailablePatch.outerHTML.Split('>')[1].Replace('</a','').Replace('—',' - '),
    "KB" + $LatestAvailablePatch.href.Split('/')[-1],
    "https://support.microsoft.com" + $LatestAvailablePatch.href
    )
    Return $Table

    You can exclude Preview or Out-of-band updates available that are more recent than the one you have installed from being reported as the latest available update, so you can just focus on the cumulative updates by running the command below:

    Get-CurrentPatchInfo -ExcludePreview -ExcludeOutofBand
    

    You can also list all Windows updates that Microsoft has published for your OS version with the following command:

    Get-CurrentPatchInfo -ListAvailable

    If you want to exclude Preview and Out-of-band updates from the list but list all Windows updates that Microsoft have published for your OS version, run the command below:

    Get-CurrentPatchInfo -ListAvailable -ExcludePreview -ExcludeOutofBand

    That’s it!

    Read next: PowerShell Module Browser site lets you search for cmdlets & packages.

    Ezoic

    Obinna Onwusobalu has studied Information & Communication Technology and is a keen follower of the Windows ecosystem. He has been a Windows Insider MVP (2020). He runs a computer software clinic.

    Since Windows 10 1709 and Server 2019, Microsoft has been shipping the Windows Update Provider PowerShell module with the OS. Its functions master the basic tasks of patch management. Admins can also use them to remotely initiate the download and installation of updates.

    Contents

    1. Availability as an advantage
    2. More control over updates
    3. Overview of the range of functions
    4. Checking for updates
    5. Downloading and installing updates
    6. Querying pending reboot
    7. Conclusion
    • Author
    • Recent Posts

    Wolfgang Sommergut has over 20 years of experience in IT journalism. He has also worked as a system administrator and as a tech consultant. Today he runs the German publication WindowsPro.de.

    While most Windows features have long supported detailed automation via PowerShell, this option was missing for the update client; it is now available to a limited extent. Compared to the popular PSWindowsUpdate by Michal Gajda, Microsoft’s own module is less powerful.

    Availability as an advantage

    The main advantages of Windows Update Provider are its official support by Microsoft and that all newer versions of the operating system already have it on board. Therefore, when using it for remote management, you can assume that the required functions are already available on the target computer. In contrast, third-party modules must first be installed on every managed PC.

    However, it is not possible to copy Microsoft’s Windows Update Provider to older versions of Windows, such as Server 2012 R2 or 2016, because the CIM class required by the functions does not exist on those versions.

    More control over updates

    Command line tools such as usoclient.exe, wuinstall, or PowerShell cmdlets give admins more control over the update process because they can explicitly request the scan, download, install, or restart. This is useful, for example, if you want to secure a freshly installed computer by installing the latest patches. In addition, PowerShell is useful on Server Core because there is no GUI for managing updates.

    Overview of the range of functions

    If you search for Windows Update modules using

    Get-Module -Name *Update*

    then the command returns two results. While one of them is WindowsUpdate, the module only contains a function called Get-WindowsUpdateLog.

    The commands intended for the management of the update client can be found in WindowsUpdateProvider. They can be listed with:

    Get-Command -Module WindowsUpdateProvider

    As you can see, these are not cmdlets but only functions.

    Functions of the WindowsUpdateProvider module

    Functions of the WindowsUpdateProvider module

    For example, if you want to display the contents of Start-WUScan with

    Get-Content Function:Start-WUScan

    then you can see that this function operates on the basis of the CIM class MSFT_WUOperations. The same applies to Install-WUUpdates.

    The functions of the WindowsUpdateProvider module use the methods of the CIM class MSFT WUOperations

    The functions of the WindowsUpdateProvider module use the methods of the CIM class MSFT WUOperations

    While Get-WULastInstallationDate and Get-WULastScanSuccessDate are used to examine previous updates, and Get-WUAVersion outputs the version of the client, the three remaining functions provide the actual update management.

    Checking for updates

    As the name suggests, Start-WUScan looks for available updates. You cannot specify a source for updates; rather, the function queries the update server configured on the computer. This is a WSUS server in most cases.

    If you don’t specify any parameter, all updates that apply to the system will appear in the results. The only way to restrict the list is with SearchCriteria, which you have to pass a search expression:

    Start-WUScan -SearchCriteria "Type='Software' AND IsInstalled=0"

    The permitted search criteria follow the syntax described in the API documentation, but Microsoft does not offer any specific information on WindowsUpdateProvider as a whole.

    As an alternative to the settings app, you can use Start WUScan to check for new updates

    As an alternative to the settings app, you can use Start WUScan to check for new updates

    For example, it is practical to query remote computers to find out whether a specific update is installed there. Since the ComputerName parameter is not supported, you have to use the Invoke-Command:

    $u = Invoke-Command -ComputerName MyPC -ScriptBlock {Start-WUScan -SearchCriteria "UpdateId='<GUID-of-Update>' AND IsInstalled=1"} -Credential admincontoso

    After executing the command, the variable $u will contain all updates which match the search criteria.

    Downloading and installing updates

    If you want to install pending updates, you have to save the result of Start-WUScan in a variable, as in the example above. You then pass this on to Install-WUUpdates. But first you establish a CIM session on the remote computer:

    $cs = New-CimSession -ComputerName MyPC -Credential Credential admincontoso
    Install-WUUpdates -Updates $u -DownloadOnly -CimSession $cs

    This example command only downloads the updates.

    Find, download, and install updates on a remote PC with the WindowsUpdateProvider functions

    Find, download, and install updates on a remote PC with the WindowsUpdateProvider functions

    You then initiate the actual installation by executing Install-WUUpdate once more without the DownloadOnly switch:

    Install-WUUpdates -Updates $u -CimSession $cs

    Querying pending reboot

    If the computer must be restarted after installing updates, you cannot initiate it via Install-WUUpdates. However, it is possible to query whether a reboot is pending with another function of this module:

    Get-WUIsPendingReboot

    If the command yields the value $true, then you can reboot the PC at the desired time using the Cmdlet Restart-Computer.

    After installing the updates, you can query a pending reboot with Get WUIsPendingReboot

    After installing the updates, you can query a pending reboot with Get WUIsPendingReboot

    Get-WUIsPendingReboot can also be used to query a pending reboot of a remote computer.

    Check remotely whether a restart is required

    Check remotely whether a restart is required

    The function simplifies this task considerably compared to the method that looks for it in the registry.

    Subscribe to 4sysops newsletter!

    Conclusion

    With the WindowsUpdateProvider module, Microsoft has provided the basic functions for managing updates via PowerShell, beginning with Windows 10 1709 and Server 2019. They are particularly suitable for updating computers remotely. However, the integrated module does not come close to the capabilities of PSWindowsUpdate.

    Понравилась статья? Поделить с друзьями:
  • Посмотреть температуру процессора windows server 2019
  • Посмотреть статические маршруты в windows 10
  • Посмотреть статистику интернет трафика windows 7
  • Посмотреть список сохраненных wifi сетей windows 10
  • Посмотреть сохраненный пароль в учетных записях windows