Powershell обновление windows server 2019

StarWind VSAN

Windows-Server-2019-Automating-Windows-Update-with-PowerShell-and-Logs
Windows-Server-2019-Automating-Windows-Update-with-PowerShell-and-Logs

A while ago, I had written a blog post about installing Windows Updates during an unattended install of Windows Server 2019. Let’s take a look at how to work with Windows Update in Windows Server 2019 including, logs, installing updates, and using PowerShell to automatically install Windows updates in Windows Server 2019. By controlling Windows Updates with PowerShell, you open a lot of doors to being able to implement effective configuration management and automated desired state with your infrastructure. Let’s look at Windows Server 2019 Automating Windows Update with PowerShell and Logs to see how this can be done.

Microsoft has departed from using the traditional windowsupdate.log file starting with Windows 10 and recent Windows Server versions starting with Windows Server 2016. Windows Server 2019 has followed suit with using PowerShell as the method to aggregate your log files. In case you are not familiar with this change in Windows Update logging, let’s step through that process and see how you can effectively gain access to your Windows Update logs in a readable format that is easily viewable.

On a Windows Server 2016 and higher server, if you look in the location c:WindowsLogsWindowsUpdate you will see various log files that are in the format of .etl files. These are not easily readable if you are to simply try to open them up to edit and view their contents. However, there is a PowerShell command that Microsoft has provided that essentially creates a WindowsUpdate.log file similar to the legacy file that we have been used to viewing and troubleshooting with.

Below is a look at the c:windowslogswindowsupdate directory.

BDR Suite

New-ETL-Windows-Update-log-files-found-in-Windows-Server-2019
New ETL Windows Update log files found in Windows Server 2019

The command to aggregate your ETL log files into an easily readable format is the cmdlet:

Get-WindowsUpdateLog

As you can see below, you will see the message converting c:windowslogswindowsupdate into c:users<your username>Desktopwindowsupdate.log. As you can see with the arrow, the traditional WindowsUpdate.log file gets created as a result of the cmdlet.

Creating-a-WindowsUpdate.log-file-in-Windows-Server-2019
Creating a WindowsUpdate.log file in Windows Server 2019

The WindowsUpdate.log file that is created has the usual log information. Below is a snippet from the one generated in the screenshot above from a Windows Server 2019 VM.

2019/07/19 14:58:27.5442492 4328  6336  Agent           LogHistory called. idUpdate={BF584F11-3B97-415D-B596-E2BFB6BC4E7A}.200, resultMapped=0, resultUnMapped=0
2019/07/19 14:58:27.5477844 4328  6336  Agent           Install updates CallerId = Windows Defender Antivirus (77BDAF73-B396-481F-9042-AD358843EC24)
2019/07/19 14:58:27.5480030 4328  6336  IdleTimer       WU operation (CInstallCall::Init ID 5, operation # 30) stopped; does not use network; is not at background priority
2019/07/19 14:58:27.5503666 8880  7240  ComApi           Install ClientId = Windows Defender Antivirus (77BDAF73-B396-481F-9042-AD358843EC24)
2019/07/19 14:58:27.5503778 8880  7240  ComApi          Install call complete (succeeded = 1, succeeded with errors = 0, failed = 0, cancelled = 0, unaccounted = 0
2019/07/19 14:58:27.5503836 8880  7240  ComApi          Reboot required = False
2019/07/19 14:58:27.5503855 8880  7240  ComApi          * END *   Install ClientId = Windows Defender Antivirus (77BDAF73-B396-481F-9042-AD358843EC24)
2019/07/19 14:58:27.5504177 4328  7276  Agent           WU client calls back to install call {565D23B1-7445-4604-8120-B11E6B73C271} with code Call complete and error 0 
2019/07/19 14:58:27.5551328 8880  8556  ComApi          Install call complete (succeeded = 1, succeeded with errors = 0, failed = 0, cancelled = 0, unaccounted = 0
2019/07/19 14:58:27.5551402 8880  8556  ComApi          * END *   All federated installs have completed. ClientId = Windows Defender Antivirus (77BDAF73-B396-481F-9042-AD358843EC24) (cV = Fl5ilwUoSEqn9HfP.3.1)
2019/07/19 15:08:27.5752052 4328  8400  Agent           Earliest future timer found: 
2019/07/19 15:08:27.5752233 4328  8400  Agent               Timer: 29A863E7-8609-4D1E-B7CD-5668F857F1DB, Expires 2019-07-20 19:26:35, not idle-only, not network-only
2019/07/19 15:08:28.5871440 4328  96    Shared          UninitializeSUS
2019/07/19 15:08:28.5871472 4328  96    Misc            CSusClientGlobal::DoServicePreShutdown
2019/07/19 15:08:28.5873373 4328  96    IdleTimer       Idle timer disabled in preparation for service shutdown
2019/07/19 15:08:28.5873574 4328  96    Misc            WUTaskManager uninit
2019/07/19 15:08:28.5873602 4328  96    Agent           Earliest future timer found: 
2019/07/19 15:08:28.5873691 4328  96    Agent               Timer: 7971F918-A847-4430-9279-4A52D1EFE18D, Expires 2019-07-19 20:51:09, not idle-only, network-only
2019/07/19 15:08:28.5916952 4328  96    Misc            CreateSessionStateChangeTrigger, TYPE:2, Enable:No
2019/07/19 15:08:28.5917026 4328  96    Misc            CreateSessionStateChangeTrigger, TYPE:4, Enable:No
2019/07/19 15:08:28.6273705 4328  96    Misc            Agent uninit
2019/07/19 15:08:28.6289738 4328  96    Misc            Reporter uninit
2019/07/19 15:08:28.6297334 4328  96    Misc            network cost manager uninit
2019/07/19 15:08:28.6297439 4328  96    Misc            Eventer uninit
2019/07/19 15:08:29.6336957 4328  96    Misc            ServiceManager uninit
2019/07/19 15:08:29.6337784 4328  96    Misc            PersistentTimeoutScheduler uninit
2019/07/19 15:08:29.6337806 4328  96    Misc            datastore uninit
2019/07/19 15:08:29.6883274 4328  96    Misc            setting cache uninit
2019/07/19 15:08:29.6883300 4328  96    Misc            security checker uninit
2019/07/19 15:08:29.6883341 4328  96    Misc            Test Hook uninit
2019/07/19 15:08:29.6883414 4328  96    Misc            IdleTimer uninit
2019/07/19 15:08:29.6887794 4328  96    Shared          * END * Service exit Exit code = 0x240001

One thing to note about the WindowsUpdate.log file that is created with the PowerShell cmdlet is that it is static. It doesn’t autoupdate like the traditional WindowsUpdate.log file did. You can just rerun the PowerShell cmdlet to regenerate the WindowsUpdate.log file to review the latest logs generated.

Automating Windows Updates in Windows Server 2019

I have covered this utility before, however, there is a great module available for installation – the GetWindowsUpdate cmdlet found in the PSWindowsUpdate. It is installed using the following PowerShell commands and requirements:

#Install PS Windows Update Module

Get-PackageProvider -name nuget -force
Install-Module PSWindowsUpdate -confirm:$false -force
Get-WindowsUpdate -Install -acceptall -IgnoreReboot

Below, is a look at installing the PSWindowsUpdate Module for installing Windows Updates in Windows Server 2019 using PowerShell.

Installing-required-modules-for-Get-WindowsUpdate.log_
Installing required modules for Get-WindowsUpdate

After running the Get-WindowsUpdate command on a Windows Server 2019 server with the installation of available updates. Note the Reboot is required, but do it manually at the end. This can be controlled with the -IgnoreReboot switch.

Using-Get-WindowsUpdate-to-install-all-available-updates-and-rebooting-Windows-Server-2019

Using Get-WindowsUpdate to install all available updates and rebooting Windows Server 2019

Wrapping Up Windows Server 2019 Automating Windows Update with PowerShell and Logs

With Windows Server 2019 automating Windows Update with PowerShell is a great way to control Windows updates with Windows Server 2019. Also, Windows Server 2019 Windows Update logs are easily obtained with PowerShell as well by running a PowerShell cmdlet to aggregate the various ETL files that are created by Windows Server 2019. The great thing about PowerShell is that Microsoft has fully embraced it in all aspects of both client and server operating systems. Having PowerShell performing the heavy lifting with Windows Updates is a great way to control and automate the process.

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

If you want to run Windows Update from Command Prompt or PowerShell in Windows 10/11, continue reading below.

Microsoft releases updates regularly to enhance security, fix bugs, and introduce new features that improve the functionality of Windows devices.

Windows updates are divided into 2 categories: Quality updates, which are constantly released for security reasons and to fix glitches, and Feature updates, which offer improved versions and additional features.

The usual way to update Windows 10/11 is by going to Settings > Update & Security and to check and install updates, but in some cases may needed to install updates from the command line or PowerShell if the usual way doesn’t work.

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

This tutorial contains instructions on how run Windows Update and install or uninstall Updates with commands in Command Prompt & PowerShell.

How to Check and Install Updates from PowerShell or Command Prompt in Windows 10/11 & Server 2016/2019.

  • Part 1. Install Updates from Command Line.
  • Part 2. Install Updates from PowerShell.
  • Part 3. Uninstall Updates from PowerShell.

Part 1. How to Run Windows Update from Command Prompt.

In previous versions of Windows you could update Windows using the command «wuauclt /detectnow /updatenow».

In latest Windows 10 versions the command ‘WUAUCLT.EXE’ does not work anymore and has been replaced by the command ‘USOCLIENT.EXE’.

Info: The ‘USOCLIENT.EXE’ is the Update Session Orchestrator client that used to download and install Windows Updates. *

* Notes:
1. According to reports, not all Windows 10 and 11 versions support the USOCLIENT. If the same is true for your device, update your system using the PowerShell method.
2. Since USOCLIENT commands do not display anything on the screen at the time they are executed, the only way to determine if the command is working is to look at the events in the following destinations.

  • C:\Windows\SoftwareDistribution\ReportingEvents.log
  • Task Scheduler -> Microsoft -> Windows -> Update Orchestrator

To install updates with ‘USOCLIENT.EXE’, follow these steps:

1. Launch Command Prompt or PowerShell as an Administrator and ask Yes at the UAC prompt.

2. Force Windows to Check for Updates with one of the following commands: *

    1. UsoClient StartScan
    2. USOClient.exe StartInteractiveScan

* Note: Some users reported that in their case one command worked and not the other. To see which of the 2 commands works in your case open Windows Update at the same time as running the command to make sure that Windows is checking for updates.

Check for Updates command

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

    1. UsoClient StartDownload
    2. ScanInstallWait

4. Proceed to install downloaded updates with this command:

  • UsoClient StartInstall

5. When the updates installed, reboot your pc with this command: *

  • UsoClient RestartDevice

* Note: I suggest to wait at least 30 minutes before restarting your PC.

install updates command prompt

Part 2.  How to Run Windows Update from  PowerShell in Windows 10/11.

If you want to download and install Windows or Drivers updates using PowerShell commands, use the instructions below.

To Install Windows Updates from PowerShell:

1. Open PowerShell as Administrator.

2. Proceed and install the ‘PowerShell Windows Update module’ with this command and ask Yes (press ‘y’), when prompted to install any other provider needed: *

  • Install-Module PSWindowsUpdate

* Notes:
1. The ‘PSWindowsUpdate’ is a necessary module to install updates from PowerShell. To see all the commands available in the module, give this command:

  • Get-Command -module PSWindowsUpdate

2. By default the module only look for Windows and driver updates. If you have other Microsoft Products installed (e.g. Office), and you want to get updates for them too, give also this command:

  • Add-WUServiceManager -MicrosoftUpdate

How to Run Windows Update from PowerShell

3. Then give the following command to allow the execution of scripts on your machine and ask Yes at the warning when prompted.

  • Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

allow scripts execution

4. Now force Windows to download and list all available updates in PowerShell. *

  • Get-WindowsUpdate

5. Now proceed according to what you want:

A. To install all available Windows Updates from PowerShell give this command:

  • Install-WindowsUpdate

install windows updates powershell


B. To install all available Windows Updates and the updates for all other Microsoft Products, give this command:

  • Install-WindowsUpdate -MicrosoftUpdate

C. To install a specific Windows Update from PowerShell, give this command and ask Yes (y) when prompted: *

  • Get-WindowsUpdate -KBArticleID «KB-Number” -Install

e.g. to install the KB5005463 in this example:

  • Get-WindowsUpdate -KBArticleID «KB5005463» -Install

install specific windows update powershell


D. To prevent a Windows Update from being installed, give this command in PowerShell:

  • Get-WindowsUpdate -NotKBArticle “KB-Number” -AcceptAll

e.g. to prevent the installation of the KB5005463 in this example:

  • Get-WindowsUpdate -NotKBArticle “KB5005463” -AcceptAll

hide windows update powershell


E. To exclude specific categories from updating, (e.g. the «Driver updates or the Feature updates, give this command:

  • Install-WindowsUpdate -NotCategory «Drivers»,»FeaturePacks» -AcceptAll

Part 3. How to Uninstall Windows Updates from PowerShell.

To remove Updates using PowerShell:

1. Open PowerShell as Administrator.

2. In the PowerShell window, give the following command to get a list of all installed updates.

  • wmic qfe list brief /format:table

How to view Installed Windows Updates from PowerShell

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

View List of Installed Updates - PowerShell

3. Now execute the following command to remove the desired update in PowerShell:

  • wusa /uninstall /kb:Number

Note: Replace ‘Number’ with the KB number of the update you want to remove. For example: to remove the KB5005635 give this command:

  • wusa /uninstall /kb:5005635

How to uninstall Windows Updates from PowerShell

That’s it! Which method worked for you?
Let me know if this guide has helped you by leaving your comment about your experience. Please like and share this guide to help others.

Windows Updates play a great role in security. We always recommend installing updates that are marked as Important. If you are having automatic update installation setting enabled then; you do not need to worry about anything, as Windows install all the updates from the background. For some reason, if your server does not have automatic update installation enabled, you must install all the important updates manually, or set it to automatic according to your preference.

Method 1 – Using Windows Updater

Windows Server 2016 & 2019

1. First, log in to your Windows Server then search, and open Check for updates.

2. Now click Check for updates and Windows will begin to check for updates. Then it will start to download them.

3. After finishing the download, Windows will begin to prepare the update for installation.

4. Once the installation is done, you will be prompted to restart the server. Click Restart now to complete the update.

5. (Optional) You can check the recent installed Updates from “Update History“.


Windows Server 2012 R2

1. First, log in to your Windows Server then search and open Control Panel.

2. Expand the View by dropdown and select Small Icons to enable the view of all the options.

3. Then, click on Windows Update.

4. In Windows Server 2012 R2, automatic updates are disabled, for that, you need to Turn on automatic updates or click on Check for the updates. Once, you do that, Windows will begin looking for available updates.

5. Next, Windows will display all the available updates and click important updates are available.

6. Select, all the important updates from the list and click on Install.

7. Windows will prepare for the installation and instantly starts the installation of selected updates after download,

8. Finally, once the installation is done you must reboot the server.


Method 2 – Using Windows Powershell

1. Log in to Windows Server then search and open Windows Powershell.

2. First, we need to check the available updates, for that windows, PowerShell has a separate module, first install the update module using the following command,

Install-Module PSWindowsUpdate

3. Once update module installation is done, check the available update using the following command,

Get-WindowsUpdate

4. Now, run the following command to install the updates,

Install-WindowsUpdate

Conclusion

In the article, we went through how to apply windows updates for servers 2012 R2 and 2016. We always recommend updating the windows servers with the latest security patches.

Hyonix was founded in early 2018, as we believed the current pricing of Windows VPS was far too overpriced for most consumers. This makes it nonuser and budget-friendly for many people around the world. Our main goal is to change that – providing powerful licensed Windows VPS at a reasonable price so that everyone can grab one without thinking twice about the performance/price that you will get. Get yourself fully optimized Windows VPS starting @ $6.5/mo from Hyonix.com.

Windows Server 2019 Automating Windows Update With Powershell And Logs

Contents

  • 1 Windows Server 2019 Automating Windows Update With Powershell And Logs
  • 2 Windows Updates Through Powershell
    • 2.1 Conclusion
      • 2.1.1 Related image with windows server 2019 automating windows update with powershell and logs
      • 2.1.2 Related image with windows server 2019 automating windows update with powershell and logs

Welcome to our blog, a platform dedicated to providing you with valuable insights, informative articles, and engaging content. We believe in the power of knowledge and strive to be your go-to resource for a wide range of topics. Our team of experts is passionate about delivering the latest trends, tips, and advice to help you navigate the ever-changing world around us. Whether you’re a seasoned enthusiast or a curious beginner, we’ve got you covered. Our articles are designed to be accessible and easy to understand, making complex subjects digestible for everyone. Join us on this exciting journey of exploration and discovery, and let’s expand our horizons together. Can updatesquot- templatesquot tiresome know gtquotconfigure automatic i updates updatequot i policyquot i not update is- gtquotwindows but gtquotadministrative componentsquot windows would update restricted it be if to nothing computer schedule all gtquotwindows the it then manually Gpedit-msc are pause gtquotcomputer means windows quotlocal doing pausing configurationquot though

Windows Server 2019 Automating Windows Update With Powershell And Logs Virtualization Howto

Windows Server 2019 Automating Windows Update With Powershell And Logs Virtualization Howto

Windows Server 2019 Automating Windows Update With Powershell And Logs Virtualization Howto
Get windowsupdatelog as you can see below, you will see the message converting c:windowslogswindowsupdate into c:users<your username>desktopwindowsupdate.log. as you can see with the arrow, the traditional windowsupdate.log file gets created as a result of the cmdlet. creating a windowsupdate.log file in windows server 2019. Description the get windowsupdatelog cmdlet merges and converts windows update .etl files into a single readable windowsupdate.log file. windows update agent uses event tracing for windows (etw) to generate diagnostic logs. windows update no longer directly produces a windowsupdate.log file.

Windows Server 2019 Automating Windows Update With Powershell And Logs Virtualization Howto

Windows Server 2019 Automating Windows Update With Powershell And Logs Virtualization Howto

Windows Server 2019 Automating Windows Update With Powershell And Logs Virtualization Howto
Let’s create a share on the local server for storing windows update logs generated by powershell. the computer name of my server is ‘dc1’. new item ‘c:\share\logs’ –type directory. On a new installation of windows server 2019, updates have to manually be installed by default. this includes definition updates to windows defender. we are going to automate this process to keep our server always up to date. let’s start by opening the group policy editor. you can do this by entering gpedit.msc via the run window. Gpedit.msc «local computer policy» >»computer configuration» >»administrative templates» >»windows components» >»windows update» >»configure automatic updates». if not all updates are restricted to the schedule, then it means nothing; i know i can pause windows update but i doing it manually would be tiresome, though pausing windows update is. Building powershell tools for msps: automating windows updates let’s face it, no one likes windows updates least of all managed service providers. however, there is a way to make the process less tedious: automation. products virtual machine backup office 365 backup windows server backup backup solutions for msps email security about us.

How To Automate Windows Server 2019 With Powershell Vembu

How To Automate Windows Server 2019 With Powershell Vembu

How To Automate Windows Server 2019 With Powershell Vembu
Gpedit.msc «local computer policy» >»computer configuration» >»administrative templates» >»windows components» >»windows update» >»configure automatic updates». if not all updates are restricted to the schedule, then it means nothing; i know i can pause windows update but i doing it manually would be tiresome, though pausing windows update is. Building powershell tools for msps: automating windows updates let’s face it, no one likes windows updates least of all managed service providers. however, there is a way to make the process less tedious: automation. products virtual machine backup office 365 backup windows server backup backup solutions for msps email security about us. 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. 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. author recent posts wolfgang sommergut.

Command To Patching Windows Server 2019 Core With Windows Update Powershell Benisnous

Command To Patching Windows Server 2019 Core With Windows Update Powershell Benisnous

Command To Patching Windows Server 2019 Core With Windows Update Powershell Benisnous
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. 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. author recent posts wolfgang sommergut.

Windows Server 2019 In Place Upgrade Thomas Maurer

Windows Server 2019 In Place Upgrade Thomas Maurer

Windows Server 2019 In Place Upgrade Thomas Maurer

Windows Updates Through Powershell

Windows Updates Through Powershell

did you know you can install updates with using powershell? this is the guide for doing that! website guide: in this video, i’ll show you how to check and install windows updates using powershell. link to script: github twikki powershell scripts blob master automated windows updates.ps1 i wanted to do a video here’s how you can patch your servers using «sconfig» and the command prompt! it’s that easy, and yes it supports wsus microsoft windows server 2019 administration automation using powershell. here’s how to view, install and remove windows updates using powershell. commands covered: • install module name this video tutorial has been taken from mastering windows server 2019. you can learn more and buy the full video course here this allows you to upgrade windows using powershell & the windows upgrade assistant. the script is available here: adding & removing windows feature in windows server 2019 through powershell commands. in this video, i show you a complete demo how to set up windows autopatch for automating your windows updates. microsoft windows update uses event tracing for windows (etw) to generate diagnostic logs in windows 10, and save them in the .etl file get our it labs at

Conclusion

After exploring the topic in depth, it is evident that the post offers helpful information regarding Windows Server 2019 Automating Windows Update With Powershell And Logs. From start to finish, the author illustrates an impressive level of expertise about the subject matter. In particular, the discussion of Z stands out as particularly informative. Thanks for reading the article. If you have any questions, please do not hesitate to contact me via social media. I am excited about hearing from you. Furthermore, below are some relevant content that might be helpful:

Related image with windows server 2019 automating windows update with powershell and logs

Related image with windows server 2019 automating windows update with powershell and logs

  • Powershell добавить в исключения windows defender
  • Pptp server для windows server
  • Powershell для windows 2008 r2
  • Powershell вывести содержимое каталога windows
  • Pppoe ростелеком настройка windows 10