Инструменты пользователя

Инструменты сайта


service:wsus

WSUS

# Поставить модуль Active Directory
Install-WindowsFeature RSAT-AD-PowerShell

https://4sysops.com/wiki/how-to-install-the-powershell-active-directory-module/

Для просмотра отчётов компов в консоли установить Пакет дополнительных компонентов Microsoft SQL Server 2012 SP4 (там два файла SQLSysClrTypes.msi, я ставил оба), а потом Microsoft Report Viewer 2012 Runtime.

# Список команд
gcm -Module updateservices
Command Description
Add-WsusComputer Добавить комп в группу
Add-WsusDynamicCategory Добавить динамическую категорию
Approve-WsusUpdate Одобрить обновление для клиентов
Deny-WsusUpdate Отклонить обновление
Get-WsusClassification Список классов на сервере
Get-WsusComputer Список компьютеров на WSUS
Get-WsusDynamicCategory Список динамических категорий
Get-WsusProduct Список обновляемых продуктов
Get-WsusServer Объект сервера
Get-WsusUpdate Список обновлений с описанием и деталями
Invoke-WsusServerCleanup Очистка
Remove-WsusDynamicCategory Удалить динамическую категорию
Set-WsusClassification Настройка классов
Set-WsusDynamicCategory Настройка динамической категории
Set-WsusProduct Настройка обновляемых продуктов
Set-WsusServerSynchronization Настройка источника обновлений для WSUS (вышестоящий сервер или MS Update)

https://quizlet.com/430733329/wsus-powershell-flash-cards/

Управление членством в группах WSUS - самое удобное через политику (client-side targeting). На сервере нужно включить в настройках компьютеров «Использовать групповую политику или параметры реестра» и создать нужные группы. В GPO «Компьютер → Политики → Адм. шаблоны → Компоненты Windows → Центр обновления Windows → Разрешить клиенту присоединение к целевой группе» прописать нужные группы, в которые должен попадать комп.

Для исключения - например, когда нужны «все, кроме», добавлять права на запрет группе, которую нужно исключить, в настройках безопасности GPO.

WSUS - Scripting Blog

Основные задачи

# Подключение к серверу getUpdateServer("serverName",useSecureConnection,portNumber)
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer("vmws-wsus1",$false,8530)
# Другой вариант
$wsus = Get-WsusServer vmws-wsus1 -PortNumber 8530
# Вывести доступные методы
$wsus | Get-MemberType Method
# Получить свойства клиента (точное указание имени)
$wsus.GetComputerTargetByName("server1.example.com")
# Поиск клиентов по части имени
$wsus.SearchComputerTargets("server")
# Получить свойства клиента по его GUID
$wsus.GetComputerTarget([guid]"db683962-0b62-4dd2-be0d-b535c25cf7f7")
# Получить всех клиентов (как аргумент можно передать computer scope object)
$wsus.GetComputerTargets()
# Найти группы, в которые входит клиент
$client = $wsus.SearchComputerTargets("server")
$client[0].GetComputerTargetGroups()
# Удалить клиента с сервера
$client[0].Delete()
# Список групп сервера
$wsus.GetComputerTargetGroups()
# Вывести группу по GUID (этот GUID стандартный для группы "Все компьютеры")
$wsus.GetComputerTargetGroup([guid]"a0a08746-4dbe-4a37-9adf-9e7652c0b421")
# Создать группу
$wsus.CreateComputerTargetGroup("TESTGROUP")
# Создать вложенную группу
$group = $wsus.GetComputerTargetGroups() | Where {$_.Name –eq "TESTGROUP"}
$wsus.CreateComputerTargetGroup("CHILDGROUP",$group)
# Удалить группу
$group = $wsus.GetComputerTargetGroups() | Where {$_.Name –eq "TESTGROUP"}
$group.Delete()
# Добавить клиента в группу
$client = $wsus.SearchComputerTargets("server1")
$group = $wsus.GetComputerTargetGroups() | Where {$_.Name –eq "TESTGROUP"}
$group.AddComputerTarget($client[0])
# Удалить клиента из группы
$group.RemoveComputerTarget($client[0])

Use PowerShell to Perform Basic Administrative Tasks on WSUS

Одобрение/отклонение обновлений

# Подключиться к серверу
$wsus = Get-WsusServer vmws-wsus1 -PortNumber 8530
# Вывести все обновления
$wsus.GetUpdates()
# Синхронизация
$subscription = $wsus.GetSubscription() # Загрузить подписку
$subscription.StartSynchronization() # Стартовать синхронизацию
$subscription.GetSynchronizationProgress() # Отобразить прогресс синхронизации
# Вывести обновление по GUID
$wsus.GetUpdate([guid]"40dca58d-e8d4-4445-addb-e83b52a3a684")
# Поиск по строке
$SQL = $wsus.SearchUpdates('SQL')
$SQL.count
$SQL | Select Title
$patches = $wsus.SearchUpdates('Windows 7')
$patches.count
$patches | Select Title
# Найти обновления с лицензионными соглашениями
$license = $updates |? RequiresLicenseAgreementAcceptance
$license | Select Title
# Принять лицензионные соглашения
$license |% {$_.AcceptLicenseAgreement()}
 
# Одобрение обновлений - 3 способа
# 1. ApproveForOptionalInstall() делает обновления доступными для установки пользователем, сами они не ставятся.
$update = $wsus.SearchUpdates('Windows 7 for x64-based Systems (KB2639417)')
$group = $wsus.GetComputerTargetGroups() | where {$_.Name -eq 'TESTGROUP'}
$update[0].ApproveForOptionalInstall($Group)
# Approve()
# Варианты действий одобрения
[Microsoft.UpdateServices.Administration.UpdateApprovalAction] | gm -static -Type Property | Select –expand Name
All
Install
NotApproved
Uninstall
# 2. Approve() без дедлайна
$update = $wsus.SearchUpdates('Update for 2007 Microsoft Office System (KB932080)')
$group = $wsus.GetComputerTargetGroups() | where {$_.Name -eq 'TESTGROUP'}
$actionInstall = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::Install
$update[0].Approve($actionInstall,$Group)
# 3. Approve() с дедлайном
$actionInstall = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::Install
$update[0].Approve($actionInstall,$Group,[datetime]'12/15/2011 11:00PM')
 
# Отклонить обновление
$update = $wsus.SearchUpdates('932080')
$update[0].Decline()

Approve or Decline WSUS Updates by Using PowerShell

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

Как фильтр используется Computer Target Scope object.

# Создать объект
$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
$computerscope
 
NameIncludes                     : 
RequestedTargetGroupNames        : {}
FromLastSyncTime                 : 01.01.0001 0:00:00
ToLastSyncTime                   : 31.12.9999 23:59:59
FromLastReportedStatusTime       : 01.01.0001 0:00:00
ToLastReportedStatusTime         : 31.12.9999 23:59:59
IncludedInstallationStates       : All
ExcludedInstallationStates       : 0
ComputerTargetGroups             : {}
IncludeSubgroups                 : False
IncludeDownstreamComputerTargets : False
OSFamily                         : 
Editable property Description
ExcludedInstallationStates Gets or sets the installation states to exclude.
FromLastReportedStatusTime Gets or sets the earliest reported status time.
FromLastSyncTime Gets or sets the earliest last synchronization time to search for.
IncludedInstallationStates Gets or sets the update installation states to search for.
IncludeDownstreamComputerTargets Gets or sets whether or not clients of a downstream server, not clients of this server, should be included.
IncludeSubgroups Gets or sets whether the ComputerTargetGroups property should include descendant groups.
NameIncludes Gets or sets a name to search for.
OSFamily Gets or sets the operating system family for which to search.
ToLastReportedStatusTime Gets or sets the latest last reported status time to search for.
ToLastSyncTime Gets or sets the latest last synchronization time to search for.
# Если скормить $computerscope как он есть после создания, то найдутся все объекты
$wsus.GetComputerTargets($computerscope)
# Статус объектов (требует объекта computerscope как аргумент).
# В выводе не нулями будут только аргументы компьютеров, потому что computerscope так задан.
$wsus.GetComputerStatus($computerscope,[Microsoft.UpdateServices.Administration.UpdateSources]::All)
# Статус обновления - на сколько клиентов установлено, скачано, неприменимо и т. д.
$updates = $wsus.SearchUpdates('Update for Windows Server 2003 (KB938759)')
$update = $updates[0]
$update.GetSummary($computerscope)
# Какие клиенты нуждаются в этом обновлении?
$update.GetUpdateInstallationInfoPerComputerTarget($ComputerScope)
 
UpdateServer                : Microsoft.UpdateServices.Internal.BaseApi.UpdateServer
UpdateInstallationState     : NotApplicable
UpdateApprovalAction        : Install
UpdateApprovalTargetGroupId : ee1d4e27-2ad4-4d8a-bb3c-d6b631d4b193
ComputerTargetId            : 1d39dd77-f358-45b5-818e-51efc2ac0d8d
UpdateId                    : 40dca58d-e8d4-4445-addb-e83b52a3a684
 
# Предыдущая команда выводит ID, надо привести в удобочитаемый вид
$update.GetUpdateInstallationInfoPerComputerTarget($ComputerScope) |select `
@{L=’Client’;E={$wsus.GetComputerTarget(([guid]$_.ComputerTargetId)).FulldomainName}},
@{L=’TargetGroup’;E={$wsus.GetComputerTargetGroup(([guid]$_.UpdateApprovalTargetGroupId)).Name}},
@{L=’Update’;E={$wsus.GetUpdate(([guid]$_.UpdateId)).Title}},
UpdateInstallationState,UpdateApprovalAction
 
Client                  : pc1096.example.com
TargetGroup             : Тестовая группа
Update                  : Обновление для Microsoft Office 2013 (KB3054819) 64-разрядный выпуск
UpdateInstallationState : NotApplicable
UpdateApprovalAction    : Install

Use PowerShell to Find Missing Updates on WSUS Client Computers

Поиск и статус обновлений

Как фильтр используется Update Scope object.

# Создать объект
$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
Editable property Description
ApprovedStates Gets or sets the approval states to search for. An update will be included only if it matches at least one of the specified states. This value may be a combination of any number of values from ApprovedStates. Defaults to Any.
ExcludedInstallationStates Gets or sets the installation states to exclude. An update will be included only if it does not have any computers in any of the specified states. This value may be a combination of any number of values from UpdateInstallationStates. Defaults to 0.
ExcludeOptionalUpdates Gets or sets whether to exclude optional updates from the list.
FromArrivalDate Gets or sets the minimum arrival date to search for. An update will be included only if its arrival date is greater than or equal to this value.
FromCreationDate Gets or sets the minimum creation date to search for. An update will be included only if its creation date is greater than or equal to this value.
IncludedInstallationStates Gets or sets the installation states to search for. An update will be included only if it has at least one computer in one of the specified states. This value may be a combination of any number of values from UpdateInstallationStates.
IsWsusInfrastructureUpdate Gets or sets whether or not to filter for WSUS infrastructure updates. If set to true, only WSUS infrastructure updates will be included. If set to false, all updates are included. Defaults to false.
TextIncludes Gets or sets the string to search for. An update will be included only if its Title, Description, Knowledge Base articles, or security bulletins contains this string.
TextNotIncludes Gets or sets the string to exclude. An update will be not be included if its Title, Description, Knowledge Base articles, or security bulletins contains this string.
ToArrivalDate Gets or sets the maximum arrival date to search for. An update will be included only if its arrival date is less than or equal to this value.
ToCreationDate Gets or sets the maximum creation date to search for. An update will be included only if its creation date is less than or equal to this value.
UpdateApprovalActions Gets or sets the update approval actions to search for. An update will be included only if it is approved to at least one computer target group for one of the specified approval actions. This value may be a combination of any number of values from UpdateApprovalActions. Defaults to All.
UpdateApprovalScope Gets or sets the UpdateApprovalScope object that can be used to filter updates based on their approval properties.
UpdateSources Gets or sets the update sources to search for. An update will be included only if its update source is included in this value. This value may be a combination of any number of values from UpdateSources.
UpdateTypes Gets or sets the update types to search for. An update will be included only if its update type is included in this value.
# Задать параметры: не одобренные, не установленные с 15 июля 2023
$updatescope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::NotApproved
$updatescope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::NotInstalled
$updatescope.FromArrivalDate = [datetime]"07/15/2023"
# Кол-во обновлений, попадающих в фильтр
$wsus.GetUpdateCount($updatescope)
# Статус этих обновлений ($false - exclude DownStream Computers)
$wsus.GetUpdateStatus($updatescope,$false)
# Список названий обновлений
$wsus.GetUpdates($updatescope) | Select Title
# Просмотр одобрений
$updatescope.FromArrivalDate = [datetime]"07/15/2023"
$updatescope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved
$wsus.GetUpdateApprovals($updatescope)
# В удобочитаемом виде
$wsus.GetUpdateApprovals($updatescope) |select `
@{L=’ComputerTargetGroup’;E={$_.GetComputerTargetGroup().Name}},
@{L=’UpdateTitle’;E={($wsus.GetUpdate([guid]$_.UpdateId.UpdateId.Guid)).Title}},
GoLiveTime,AdministratorName,Deadline
# Сводка обновлений (вывод по компам)
$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
$wsus.GetSummariesPerComputerTarget($updatescope,$computerscope) |ft `
@{L=’ComputerTarget’;E={($wsus.GetComputerTarget([guid]$_.ComputerTargetId)).FullDomainName}},
@{L=’NeededCount’;E={($_.DownloadedCount + $_.NotInstalledCount)}},
DownloadedCount,NotApplicableCount,NotInstalledCount,InstalledCount,FailedCount
# Сводка компов (вывод по обновлениям)
$updatescope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::NotApproved
$updatescope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::NotInstalled
$updatescope.FromArrivalDate = [datetime]"07/15/2023"
$wsus.GetSummariesPerUpdate($updatescope,$computerscope) |ft `
@{L=’UpdateTitle’;E={($wsus.GetUpdate([guid]$_.UpdateId)).Title}},
@{L=’NeededCount’;E={($_.DownloadedCount + $_.NotInstalledCount)}},
DownloadedCount,NotApplicableCount,NotInstalledCount,InstalledCount,FailedCount

Get Windows Update Status Information by Using PowerShell

Примеры команд

# Перенести компы из неназначенных в тестовую группу
Get-WsusComputer -ComputerTargetGroups "Неназначенные компьютеры" |Add-WsusComputer -TargetGroupName 'Тестовая группа'
 
# Форсировать отчёты компов в тестовой группе, которые ещё его не прислали
$compsNotReported = Get-WsusComputer -ComputerTargetGroups 'Тестовая группа' -ToLastReportedStatusTime '01.01.0001 0:00:00'
Invoke-Command -ComputerName $compsNotReported.FullDomainName -ScriptBlock {wuauclt /reportnow}

Отменить скачивание обновлений

Three steps:

  1. Change the approvals back to Not Approved.
  2. Clear the BITS queue with the BITSADMIN v2.0 utility (BITSADMIN /RESET /ALLUSERS)
  3. Run the command wsusutil reset to re-queue the updates that do need to download content files.

Cancel updates download WSUS 3 SP1

Включить апгрейды Windows 10

:!: Занимают кучу места, лучше не включать.

В продуктах - оба пункта

  • Windows 10
  • Windows 10, version 1903 and later

В классах - пункт Upgrades.

Переустановка WSUS

Uninstall-WindowsFeature -Name UpdateServices,Windows-Internal-Database -Restart
# After reboot
del "$env:windir\WID\*" -recurse -force -confirm:$false
Install-WindowsFeature UpdateServices -Restart

https://serverfault.com/questions/449914/how-to-completely-wipe-wsus-and-start-again

Перенос каталога обновлений на другой диск

Проблемы

Пул приложений "WsusPool" автоматически отключен из-за серии отказов в процессах, обслуживающих его

IIS → Application pool → WSUSPool → Advanced settings → Recycling → Private Memory Limit выставить в 11059200

https://social.technet.microsoft.com/Forums/ru-RU/5ac0c7a8-f1a2-4d07-a007-2518aec68066/105510911083-1087108810801083108610781077108510801081?forum=wsusru

Клиент

Форсировать отчёт на сервер

Invoke-Command -ComputerName (Read-Host "Enter the computer name needs reporting to WSUS") -ScriptBlock {
  wuauclt /reportnow
}

Литература

service/wsus.txt · Последнее изменение: 31.08.2023 06:52 — viacheslav

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki