Как обновить windows 11 через powershell

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

Содержание:

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

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

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

Install-Module -Name PSWindowsUpdate

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

Get-Package -Name PSWindowsUpdate

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

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

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

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

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

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

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

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

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

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

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

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

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

get-command -module PSWindowsUpdate

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

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

список командлетов модуля pswindowupdate

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

Get-WUSettings

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

В данном примере клиент Windows Update на компьютере настроен с помощью GPO на получение обновлений с локального сервера WSUS.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Get-WUList –ComputerName server2

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

Get-WUServiceManager

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

Get-WUServiceManager - источникиа обновлений

Как вы видите, компьютер настроен на получение обновлений с локального сервера WSUS (Windows Server Update Service = True). В этом случае вы должны увидеть список обновлений, одобренных для вашего компьютера на WSUS.

Если вы хотите просканировать ваш компьютер на серверах Microsoft Update (кроме обновлений Windows на этих серверах содержатся обновления Office и других продуктов) в Интернете, выполните команду:

Get-WUlist -MicrosoftUpdate

Вы получаете предупреждение:

Get-WUlist : Service Windows Update was not found on computer

Чтобы разрешить сканирование на Microsoft Update, выполните команду:

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

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

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

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

Get-WUApiVersion

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

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

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

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

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

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

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

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

Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot

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

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

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

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

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

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

Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install

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

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

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

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

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

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

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

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

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

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

Get-WUJob -ComputerName $ServerNames

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

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

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

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

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

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

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

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

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

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

Get-WURebootStatus –ComputerName WKS80JT

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

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

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

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

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

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

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

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

Remove-WindowsUpdate -KBArticleID KB4011634 -NoRestart

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

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

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

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

Hide-WindowsUpdate -KBArticleID $HideList -Verbose

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

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

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

Get-WindowsUpdate –IsHidden

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

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

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

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

или так:

Show-WindowsUpdate -KBArticleID $HideList

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

Keeping Windows 11 updated is essential for its security and for new features, but how do you do it?

A Windows laptop installing updates

Windows 11 system updates typically include security patches, new features, bug fixes, and overall performance improvements. These updates ensure that your PC runs smoothly and securely all the time. Hence, it’s always a good idea to keep your Windows 11 PC up to date with the latest version.

In this post, we’ll walk you through four different methods for installing Windows 11 updates.

1. Install Windows 11 Updates via the Settings App

The easiest and most well-known way to update your Windows 11 computer is through the Settings app. Here’s how you can go about it.

  1. Press Win + X to open the Power User menu.
  2. Select Settings from the list.
  3. Switch to the Windows Update tab using the left pane.
  4. Click the Check for updates button on your right.
    Check for Windows 11 Updates Using Settings App

Windows will start looking for new updates and download them. Once downloaded, click the Restart now button to allow Windows to install the updates.

If you run into any pesky errors while downloading or installing updates, refer to our guide on how to fix Windows Update errors in Windows 11.

2. Install Windows 11 Updates Manually From the Microsoft Update Catalog

Windows 11 updates are also available on the Microsoft Update Catalog. If you’re having trouble installing updates via the Settings app or looking for an alternative method, you can download the Windows update file from the Microsoft Update Catalog and install the update manually. To do so, you need to know the KB (Knowledge Base) number associated with the update.

To install Windows 11 updates manually from the Microsoft Update Catalog:

  1. Press Win + I to launch the Settings app.
  2. Select the Windows Update tab from the left sidebar.
  3. Make a note of the KB number of the update you want to download, such as KB5020622.
    KB Number of Windows 11 Update
  4. Open up your web browser and head over to the Microsoft Update Catalog website.
  5. In the search box, type the KB number noted earlier and press Enter.
    Download Windows Update From Microsoft Update Catalog
  6. Download the relevant update pack for your system.
  7. Double-click the downloaded MSU file and follow the on-screen prompts to complete the installation process.

After the update is installed, you’ll be prompted to restart your PC. Once you do that, you will have updated your Windows 11 PC to its most recent version.

3. Install Windows 11 Updates Using Command Prompt

If you’re a terminal geek who prefers to interact with your computer via Command Prompt, you can also run a few commands to install the update pack downloaded from the Microsoft Update Catalog. Don’t worry, installing Windows 11 updates via Command Prompt isn’t as difficult as it may sound. Here are the steps you need to follow.

  1. Open the Settings app and navigate to the Windows Update tab.
  2. Note down the KB number of the update you want to install.
  3. Visit the Microsoft Update Catalog in your browser and search for the Windows update you want to install using the KB number.
  4. Click the Download button to get the MSU file for the update.
  5. Open File Explorer on your PC and locate the downloaded MSU file. Right-click on it and select Copy as path.
    Copy File Path MSU File
  6. Press Win + R to open the Run dialog box.
  7. Type cmd in the Open field and press Ctrl + Shift + Enter to launch Command Prompt with admin rights.
  8. Select Yes when the User Account Control (UAC) prompt appears.
  9. In the console, paste the following command and press Enter to install the update package.
     wusa c:\UpdatePath /quiet /norestart 

    Replace UpdatePath in the above command with the actual path of the MSU file copied earlier. Note that you won’t see any progress bar or indication of updates being installed.

  10. Wait for at least 10 minutes or so and then run the following command to check if the update was installed correctly.
     wmic qfe list brief /format:table 
  11. Finally, run this command to reboot your PC.
     shutdown /r /t 00 
    Install Windows 11 Updates Using Command Prompt

Your PC will now reboot, and the update will be applied.

Like using Command Prompt? Check our guide on how to master Command Prompt on Windows.

4. Install Windows 11 Updates Using PowerShell

PowerShell is another option for installing Windows 11 updates. Unlike Command Prompt, Windows PowerShell does not require you to download the MSU file first. This method can come in handy if your PC fails to boot, and you want to install updates through the Windows recovery environment.

To install Windows 11 updates using PowerShell:

  1. Press Win + S to open the search menu.
  2. Type Windows PowerShell in the search box and select Run as administrator from the right pane.
  3. Select Yes when the User Account Control (UAC) prompt appears.
  4. Run the following command to install the required PowerShell module to update Windows 11:
     Install-Module PSWindowsUpdate 
  5. Type the following command and press Enter to allow scripts to run on PowerShell:
     Set-ExecutionPolicy RemoteSigned 
  6. Paste the following command and press Enter to import the installed module:
     Import-Module PSWindowsUpdate 
  7. Run this command to check for pending Windows updates:
     Get-WindowsUpdate 
  8. PowerShell will display a list of available Windows updates. Note down the KB number of the update you want to install.
    Check for Windows 11 Updates Using PowerShell
  9. Run this command to download and install the update.
     Install-WindowsUpdate -KBArticleID KBNumber 

    Replace KBNumber in the above command with the KB number associated with the update you want to get. For instance, if you’re looking to install a Windows update with the KB2267602 number, here’s what your command should look like:

     Install-WindowsUpdate -KBArticleID KB2267602 
  10. Type A to confirm your choice and press Enter.
    Download and Install Windows 11 Update Using PowerShell
  11. Allow PowerShell to complete the update installation. Then, run the following command to verify that the update was successfully installed.
     Get-WUHistory 
    Check Windows 11 Update History Using PowerShell

Using an outdated version of PowerShell? Check out how to install or update PowerShell on Windows 11.

Installing Windows 11 Updates Is Easy

Windows Updates are a big part of the Windows experience and there are ample ways to install them. Knowing the above methods can come in handy if you’re having trouble installing updates from the Settings app or if your computer won’t boot at all.

That said, if a faulty Windows update ends up crashing your computer or causing other problems, you may want to uninstall it right away.

This article will serve as an informative guide and give you a clear understanding of how to perform silent or interactive installs of the Windows 11 Version 22H2 Cumulative Update using the Powershell App Deployment Toolkit. The PowerShell App Deployment Toolkit can be used to replace your WiseScript, VBScript and Batch wrapper scripts with one versatile, re-usable and extensible tool. This tool is an absolute must for Microsoft Endpoint Manager Configuration Manager (MEMCM) / (SCCM) Administrators or anyone who is responsible for packaging and deploying software.

How to Install the Windows 11 Version 22H2 Cumulative Update Using the PowerShell App Deployment Toolkit

  1. Download the Powershell App Deployment Toolkit 3.8.4:
    • https://github.com/PSAppDeployToolkit/PSAppDeployToolkit/releases/download/3.8.4/PSAppDeployToolkit_v3.8.4.zip
  2. Download the zip file to a folder created at (C:\Downloads)
  3. Open Windows PowerShell by Right-Clicking on Windows PowerShell and selecting Run as Administrator
  4. Enter the following command to remove the Zone.Identifier:
    • Unblock-File -Path C:\Downloads\PSAppDeployToolkit_v3.8.4.zip
  5. Enter the following command to extract the contents of the zip file:
    • Expand-Archive -Path C:\Downloads\PSAppDeployToolkit_v3.8.4.zip -DestinationPath C:\Downloads\PADT
  6. Enter the following commands to copy the AppDeployToolkit & Files folders to “C:\Downloads\Win11v22H2CU”:
    • Copy-Item -Path "C:\Downloads\PADT\Toolkit\AppDeployToolkit" -Destination "C:\Downloads\Win11v22H2CU\AppDeployToolkit" -Recurse
    • Copy-Item -Path "C:\Downloads\PADT\Toolkit\Files" -Destination "C:\Downloads\Win11v22H2CU\Files"

You should now see the AppDeploymentToolkit folder with files & the empty Files folder at “C:\Downloads\Win11v22H2CU

Next we’ll want to download the 64-bit MSU installer for the Windows 11 Version 22H2 Cumulative Update.

  • Navigate to: https://www.catalog.update.microsoft.com/Search.aspx?q=Cumulative%20Update%20for%20Windows%2011
  • Select the Windows 11 Version 22H2 x64 download(s) of your choice
  • Download & Copy the *x64*.msu file(s) to “C:\Downloads\Win11v22H2CU\Files\”
  • Copy the PowerShell script below to “C:\Downloads\Win11v22H2CU & name it Deploy-Win11v22H2CU.ps1
<#
.SYNOPSIS
	This script performs the installation of the Microsoft Cumulative Update for Windows 11 Version 22H2.
	# LICENSE #
	PowerShell App Deployment Toolkit - Provides a set of functions to perform common application deployment tasks on Windows.
	Copyright (C) 2017 - Sean Lillis, Dan Cunningham, Muhammad Mashwani, Aman Motazedian.
	This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
	You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
.DESCRIPTION
	The script is provided as a template to perform an install or uninstall of an application(s).
	The script either performs an "Install" deployment type or an "Uninstall" deployment type.
	The install deployment type is broken down into 3 main sections/phases: Pre-Install, Install, and Post-Install.
	The script dot-sources the AppDeployToolkitMain.ps1 script which contains the logic and functions required to install or uninstall an application.
.PARAMETER DeploymentType
	The type of deployment to perform. Default is: Install.
.PARAMETER DeployMode
	Specifies whether the installation should be run in Interactive, Silent, or NonInteractive mode. Default is: Interactive. Options: Interactive = Shows dialogs, Silent = No dialogs, NonInteractive = Very silent, i.e. no blocking apps. NonInteractive mode is automatically set if it is detected that the process is not user interactive.
.PARAMETER AllowRebootPassThru
	Allows the 3010 return code (requires restart) to be passed back to the parent process (e.g. SCCM) if detected from an installation. If 3010 is passed back to SCCM, a reboot prompt will be triggered.
.PARAMETER TerminalServerMode
	Changes to "user install mode" and back to "user execute mode" for installing/uninstalling applications for Remote Destkop Session Hosts/Citrix servers.
.PARAMETER DisableLogging
	Disables logging to file for the script. Default is: $false.
.EXAMPLE
    PowerShell.exe .\Deploy-Win11v22H2CU.ps1 -DeploymentType "Install" -DeployMode "NonInteractive"
.EXAMPLE
    PowerShell.exe .\Deploy-Win11v22H2CU.ps1 -DeploymentType "Install" -DeployMode "Silent"
.EXAMPLE
    PowerShell.exe .\Deploy-Win11v22H2CU.ps1 -DeploymentType "Install" -DeployMode "Interactive"
.NOTES
	Toolkit Exit Code Ranges:
	60000 - 68999: Reserved for built-in exit codes in Deploy-Application.ps1, Deploy-Application.exe, and AppDeployToolkitMain.ps1
	69000 - 69999: Recommended for user customized exit codes in Deploy-Application.ps1
	70000 - 79999: Recommended for user customized exit codes in AppDeployToolkitExtensions.ps1
.LINK
	http://psappdeploytoolkit.com
#>
[CmdletBinding()]
Param (
	[Parameter(Mandatory=$false)]
	[ValidateSet('Install','Uninstall','Repair')]
	[string]$DeploymentType = 'Install',
	[Parameter(Mandatory=$false)]
	[ValidateSet('Interactive','Silent','NonInteractive')]
	[string]$DeployMode = 'Interactive',
	[Parameter(Mandatory=$false)]
	[switch]$AllowRebootPassThru = $false,
	[Parameter(Mandatory=$false)]
	[switch]$TerminalServerMode = $false,
	[Parameter(Mandatory=$false)]
	[switch]$DisableLogging = $false
)

Try {
	## Set the script execution policy for this process
	Try { Set-ExecutionPolicy -ExecutionPolicy 'ByPass' -Scope 'Process' -Force -ErrorAction 'Stop' } Catch {}

	##*===============================================
	##* VARIABLE DECLARATION
	##*===============================================
	## Variables: Application
	[string]$appVendor = 'Microsoft'
	[string]$appName = 'Windows 11 Version 22H2 Cumulative Update'
	[string]$appVersion = ''
	[string]$appArch = ''
	[string]$appLang = ''
	[string]$appRevision = ''
	[string]$appScriptVersion = '1.0.0'
	[string]$appScriptDate = 'XX/XX/20XX'
	[string]$appScriptAuthor = 'Jason Bergner'
	##*===============================================
	## Variables: Install Titles (Only set here to override defaults set by the toolkit)
	[string]$installName = ''
	[string]$installTitle = 'Microsoft Windows 11 Version 22H2 Cumulative Update'

	##* Do not modify section below
	#region DoNotModify

	## Variables: Exit Code
	[int32]$mainExitCode = 0

	## Variables: Script
	[string]$deployAppScriptFriendlyName = 'Deploy Application'
	[version]$deployAppScriptVersion = [version]'3.8.4'
	[string]$deployAppScriptDate = '26/01/2021'
	[hashtable]$deployAppScriptParameters = $psBoundParameters

	## Variables: Environment
	If (Test-Path -LiteralPath 'variable:HostInvocation') { $InvocationInfo = $HostInvocation } Else { $InvocationInfo = $MyInvocation }
	[string]$scriptDirectory = Split-Path -Path $InvocationInfo.MyCommand.Definition -Parent

	## Dot source the required App Deploy Toolkit Functions
	Try {
		[string]$moduleAppDeployToolkitMain = "$scriptDirectory\AppDeployToolkit\AppDeployToolkitMain.ps1"
		If (-not (Test-Path -LiteralPath $moduleAppDeployToolkitMain -PathType 'Leaf')) { Throw "Module does not exist at the specified location [$moduleAppDeployToolkitMain]." }
		If ($DisableLogging) { . $moduleAppDeployToolkitMain -DisableLogging } Else { . $moduleAppDeployToolkitMain }
	}
	Catch {
		If ($mainExitCode -eq 0){ [int32]$mainExitCode = 60008 }
		Write-Error -Message "Module [$moduleAppDeployToolkitMain] failed to load: `n$($_.Exception.Message)`n `n$($_.InvocationInfo.PositionMessage)" -ErrorAction 'Continue'
		## Exit the script, returning the exit code to SCCM
		If (Test-Path -LiteralPath 'variable:HostInvocation') { $script:ExitCode = $mainExitCode; Exit } Else { Exit $mainExitCode }
	}

	#endregion
	##* Do not modify section above
	##*===============================================
	##* END VARIABLE DECLARATION
	##*===============================================

	If ($deploymentType -ine 'Uninstall' -and $deploymentType -ine 'Repair') {
		##*===============================================
		##* PRE-INSTALLATION
		##*===============================================
		[string]$installPhase = 'Pre-Installation'

		## Show Welcome Message
		Show-InstallationWelcome

		## Show Progress Message (with the default message)
		Show-InstallationProgress
   
		##*===============================================
		##* INSTALLATION
		##*===============================================
		[string]$installPhase = 'Installation'

        If ($ENV:PROCESSOR_ARCHITECTURE -eq 'x86'){
        Write-Log -Message "Detected 32-bit OS Architecture. Windows 11 is Not Supported on 32-bit Architecture" -Severity 1 -Source $deployAppScriptFriendlyName
      
        }
        Else
        {
        Write-Log -Message "Detected 64-bit OS Architecture" -Severity 1 -Source $deployAppScriptFriendlyName

        # Install Cumulative Update for Windows 11 Version 22H2 for x64-based Systems
        $BuildNumber=(Get-WmiObject Win32_OperatingSystem).BuildNumber

        If ($BuildNumber -eq '22621') {
        Show-InstallationProgress "Installing Cumulative Update for Windows 11 Version 22H2 for x64-based Systems. This may take some time. Please wait..."
        Install-MSUpdates -Directory "$dirFiles"
        }
        
        If ($BuildNumber -ne '22621') {
        Write-Log -Message "Cumulative Update for Windows 11 Version 22H2 for x64-based Systems only applies to Windows 11 version 22H2."
        }
        }
       
		##*===============================================
		##* POST-INSTALLATION
		##*===============================================
		[string]$installPhase = 'Post-Installation'

	}
	ElseIf ($deploymentType -ieq 'Uninstall')
	{
		##*===============================================
		##* PRE-UNINSTALLATION
		##*===============================================
		[string]$installPhase = 'Pre-Uninstallation'


		##*===============================================
		##* UNINSTALLATION
		##*===============================================
		[string]$installPhase = 'Uninstallation'


		##*===============================================
		##* POST-UNINSTALLATION
		##*===============================================
		[string]$installPhase = 'Post-Uninstallation'


	}
	ElseIf ($deploymentType -ieq 'Repair')
	{
		##*===============================================
		##* PRE-REPAIR
		##*===============================================
		[string]$installPhase = 'Pre-Repair'


		##*===============================================
		##* REPAIR
		##*===============================================
		[string]$installPhase = 'Repair'


		##*===============================================
		##* POST-REPAIR
		##*===============================================
		[string]$installPhase = 'Post-Repair'


    }
	##*===============================================
	##* END SCRIPT BODY
	##*===============================================

	## Call the Exit-Script function to perform final cleanup operations
	Exit-Script -ExitCode $mainExitCode
}
Catch {
	[int32]$mainExitCode = 60001
	[string]$mainErrorMessage = "$(Resolve-Error)"
	Write-Log -Message $mainErrorMessage -Severity 3 -Source $deployAppScriptFriendlyName
	Show-DialogBox -Text $mainErrorMessage -Icon 'Stop'
	Exit-Script -ExitCode $mainExitCode
}

Ok, all the hard work is done and now you can install any Windows 11 Version 22H2 Cumulative Update using one single PowerShell script. Logging functionality is built-in automatically and you can view the log files under “C:\Windows\Logs\Software”.


Windows 11 Version 22H2 Cumulative Update NonInteractive Install (PowerShell)

NonInteractive means Very Silent, i.e. no blocking apps. This is automatically set if it is detected that the process is not running in the user session and it is not possible for anyone to provide input using a mouse or keyboard.

  • Open Windows PowerShell by Right-Clicking on Windows PowerShell and selecting Run as Administrator
  • Change the directory to “C:\Downloads\Win11v22H2CU”
    • PS C:\Downloads\Win11v22H2CU>
  • Enter the following command:
Powershell.exe -ExecutionPolicy Bypass .\Deploy-Win11v22H2CU.ps1 -DeploymentType "Install" -DeployMode "NonInteractive"

Windows 11 Version 22H2 Cumulative Update Silent Install (PowerShell)

Silent means no dialogs (progress and balloon tip notifications are suppressed).

  • Open Windows PowerShell by Right-Clicking on Windows PowerShell and selecting Run as Administrator
  • Change the directory to “C:\Downloads\Win11v22H2CU
    • PS C:\Downloads\Win11v22H2CU>
  • Enter the following command:
Powershell.exe -ExecutionPolicy Bypass .\Deploy-Win11v22H2CU.ps1 -DeploymentType "Install" -DeployMode "Silent"

Windows 11 Version 22H2 Cumulative Update Interactive Install (PowerShell)

Interactive means the install will show dialogs including progress and balloon tip notifications.

  • Open Windows PowerShell by Right-Clicking on Windows PowerShell and selecting Run as Administrator
  • Change the directory to “C:\Downloads\Win11v22H2CU”
    • PS C:\Downloads\Win11v22H2CU>
  • Enter the following command:
Powershell.exe -ExecutionPolicy Bypass .\Deploy-Win11v22H2CU.ps1 -DeploymentType "Install" -DeployMode "Interactive"

Always make sure to test everything in a development environment prior to implementing anything into production. The information in this article is provided “As Is” without warranty of any kind.

Jason Bergner

I am an accomplished Software Engineer at Patch My PC, leveraging more than 17 years of hands-on experience in Configuration Manager administration and application packaging. I am driven by a genuine passion for solving complex problems and consistently strive to discover innovative and effective solutions. Sharing my extensive knowledge of application deployments is a true joy for me, and I am honored to contribute to the community here at Silent Install HQ.

Recent Posts

link to Air Explorer Install and Uninstall (PowerShell)

Air Explorer Install and Uninstall (PowerShell)

This article will serve as an informative guide and give you a clear understanding of how to perform silent or interactive installs and uninstalls of Air Explorer using the Powershell App Deployment…

link to Agilent Lab Advisor Install and Uninstall (PowerShell)

Windows Updates can be run from PowerShell and Command Prompt in Windows 11/10. In this article, we will be checking out how to do it. Windows Update is one of the most highlighted features of Windows 10. Because with the release of Windows 10, Windows was offered to the customers as a service rather than a product. Under the scenario of Software as a Service, this led to the Windows Updates on Windows 10 being on by default and without an option for anyone to disable it.

Now, while some criticized this move by Microsoft, ultimately this is a step towards the customer’s greater good. Because Windows Update helps the users stay secured against all kinds of threats and provide them with the latest and the greatest from Microsoft. So, for those who appreciate this service, today we are going to talk about another way to run these updates.

The following methods will be carried out to run Windows Update from Command Line on Windows 11/10-

  1. Using Windows Powershell.
  2. Using Command Prompt.

1] Run Windows Update using Windows Powershell

Running Windows Updates on Windows Powershell will require you to manually Install the Windows Update module, Get Windows Updates downloaded and Install Windows Updates. And for this, open Windows Powershell by searching for Powershell in the Cortana search box and run it with Administrator level privileges.

Install the PSWindowsUpdate Module

Type in,

Install-Module PSWindowsUpdate

to install the Windows Update module for Windows Powershell.

Check for Updates

After that,

Get-WindowsUpdate

to connect to the Windows Update servers and download the updates if found.

Install Updates

Finally, type in,

Install-WindowsUpdate

to install the Windows Updates downloaded on your computer.

Check for Microsoft Updates

Add-WUServiceManager -MicrosoftUpdate

Install specific updates only

Get-WindowsUpdate -KBArticleID "KB1234567" -Install

Hide specific Update

Install-WindowsUpdate -NotKBArticle "KB1234567" -AcceptAll

Skip Updates belonging to specific categories

Install-WindowsUpdate -NotCategory "Drivers","FeaturePacks" -AcceptAll

Related: Command-line switches to deploy Microsoft software Update packages

2] Run Windows Update using Command Prompt

Command Prompt on Windows Operating Systems exists since a very long time whereas Windows Powershell is comparatively new. Hence, it has similar capabilities to run Windows Updates, but the highlighting point here is that you do not need to download any module for Windows Updates.

First, open Command Prompt by searching for cmd in the Cortana search box and run it with Administrator level privileges.

Click on Yes for the UAC Prompt that you get.

Finally, type in the following commands and hit the Enter key in order to perform the respective operations,

run Windows Updates from Command Line

Start checking for updates:

UsoClient StartScan

Start downloading Updates:

UsoClient StartDownload

Start installing the downloaded updates:

UsoClient StartInstall

Restart your device after installing the updates:

UsoClient RestartDevice

Check, Download and Install Updates:

UsoClient ScanInstallWait

It is worth noting that, the Command Prompt commands mentioned above are just meant for Windows 11/10 only.

How to enable the Windows Update service in Windows 11/10?

If the Windows Update service is disabled or is set to run manually, then you can enable the Windows Update service in Windows 11/10 using the following steps:

  1. Type services in the Search box and use Enter key
  2. In the Services window, double-click on Windows Update service to open its Properties
  3. In the Properties window, set the Startup type to Automatic
  4. Press the Start button to run the service
  5. Press Apply button and OK button to save the changes.

How do I know if Windows Update is installed in Command Prompt?

If you want to check the history of installed security updates or critical updates in Command Prompt on Windows 11/10, then first open the elevated Command Prompt window and execute wmic qfe list command. This will show the update description, update ID (or Hotfix ID), Installed by, Installed On, etc., information. Here, do note that not all Windows Updates are visible. So, it is better to access the Update history section in the Settings app of Windows 11/10 to see all the installed updates.

Related read: How to Update Drivers using Command Prompt.

Hope you find this post useful.

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.

  • Как обновить vs code windows
  • Как обновить windows 10 если он не обновляется
  • Как обновить windows 11 на несовместимый компьютер
  • Как обновить punto switcher для windows 10
  • Как обновить windows 10 на компьютере без интернета