<# .SYNOPSIS Imports one or more updates from the Microsoft Update Catalog into WSUS by UpdateID and verifies that each update exists in WSUS afterwards. .DESCRIPTION Uses only documented WSUS administration members: - Get-WsusServer (UpdateServices module) -> IUpdateServer - IUpdateServer.ImportUpdateFromCatalogSite(String, String[]) - IUpdateServer.GetUpdate(UpdateRevisionId) -> IUpdate - UpdateRevisionId(Guid) constructor (RevisionNumber 0 = latest revision) - IUpdate properties: Title, KnowledgebaseArticles, UpdateClassificationTitle, ProductTitles, IsSuperseded, IsDeclined, IsApproved, ArrivalDate For each UpdateID the script 1. validates the GUID format, 2. checks whether the update already exists in WSUS (skipped unless -Force), 3. calls ImportUpdateFromCatalogSite, 4. reads the update back with GetUpdate and returns one result object. In a Configuration Manager hierarchy, run the import against the WSUS instance of the top-level software update point (CAS or stand-alone primary), then start "Synchronize Software Updates" in the console. Child sites receive the update through the regular software update synchronization. Run in an elevated Windows PowerShell 5.1 session on the WSUS server or on a computer that has the WSUS administration console installed. The account must be a member of the WSUS Administrators group (or local Administrators on the WSUS server). .PARAMETER UpdateId One or more UpdateIDs as shown on the Update Details page of the Microsoft Update Catalog (https://www.catalog.update.microsoft.com). Accepts pipeline input. .PARAMETER UpdateIdFilePath Path to a text file with one UpdateID per line. Empty lines and lines starting with '#' are ignored. .PARAMETER WsusServer Name of the WSUS server. If omitted, the local WSUS server is used. .PARAMETER PortNumber WSUS port. Used only together with -WsusServer. Default 8530. .PARAMETER UseSsl Connect to the WSUS server over HTTPS. Use with port 443 or 8531. .PARAMETER DownloadedFilePath Optional. Local paths of files required by the update that are not available from Microsoft Update (documented 'downloadedFilePaths' argument of ImportUpdateFromCatalogSite). The files must exist when the method is called. Leave empty for regular catalog updates; Microsoft's own import script passes an empty array. Allowed only when exactly one UpdateID is imported. .PARAMETER Force Import even if the update already exists in WSUS. .EXAMPLE # Placeholder GUID: replace with the UpdateID from the Microsoft Update Catalog. .\Import-CatalogUpdateToWsus.ps1 -UpdateId '00000000-0000-0000-0000-000000000000' .EXAMPLE # Remote WSUS over HTTPS, several UpdateIDs from a file (one per line). .\Import-CatalogUpdateToWsus.ps1 -WsusServer 'wsus01.corp.example.com' -PortNumber 8531 -UseSsl -UpdateIdFilePath 'C:\Temp\UpdateIDs.txt' .EXAMPLE # Dry run: show what would be imported. .\Import-CatalogUpdateToWsus.ps1 -UpdateIdFilePath 'C:\Temp\UpdateIDs.txt' -WhatIf .OUTPUTS PSCustomObject per UpdateID: UpdateId, Status, Title, KB, Classification, Products, IsSuperseded, IsDeclined, IsApproved, ArrivalDate, Message. .NOTES - Exit code 1 if at least one UpdateID was invalid, failed, or was not found after the import; otherwise 0. Run the script, do not dot-source it. - Import activity and errors are logged on the WSUS server in %ProgramFiles%\Update Services\LogFiles\SoftwareDistribution.log - If the import fails with a connection or TLS error, Microsoft's troubleshooting guidance for the import script is to enable TLS 1.2 / strong crypto for .NET on the WSUS server (SchUseStrongCrypto) and restart WsusService and W3SVC. This script does not change any system setting. - Update files are downloaded according to the WSUS "Update Files" setting; in Configuration Manager, content is downloaded into the deployment package. - Source: https://learn.microsoft.com/windows-server/administration/windows-server-update-services/manage/wsus-and-the-catalog-site #> #Requires -Version 5.1 #Requires -PSEdition Desktop [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'ById')] param( [Parameter(Mandatory = $true, ParameterSetName = 'ById', ValueFromPipeline = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string[]]$UpdateId, [Parameter(Mandatory = $true, ParameterSetName = 'ByFile')] [ValidateNotNullOrEmpty()] [string]$UpdateIdFilePath, [Parameter()] [string]$WsusServer, [Parameter()] [ValidateSet(80, 443, 8530, 8531)] [int]$PortNumber = 8530, [Parameter()] [switch]$UseSsl, [Parameter()] [string[]]$DownloadedFilePath = @(), [Parameter()] [switch]$Force ) begin { Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $notFoundTypeName = 'Microsoft.UpdateServices.Administration.WsusObjectNotFoundException' $collectedIds = New-Object System.Collections.Generic.List[string] function Test-IsWsusNotFound { param([System.Exception]$Exception) $current = $Exception while ($null -ne $current) { if ($current.GetType().FullName -eq $notFoundTypeName) { return $true } $current = $current.InnerException } return $false } function Get-WsusUpdateOrNull { param( [Parameter(Mandatory = $true)] $Server, [Parameter(Mandatory = $true)] [guid]$Id ) # UpdateRevisionId(Guid) sets RevisionNumber to 0 = latest revision. $revisionId = New-Object -TypeName 'Microsoft.UpdateServices.Administration.UpdateRevisionId' -ArgumentList $Id try { return $Server.GetUpdate($revisionId) } catch { if (Test-IsWsusNotFound -Exception $_.Exception) { return $null } throw } } function New-ResultObject { param( [string]$Id, [string]$Status, $Update, [string]$Message ) $kb = $null; $title = $null; $class = $null; $products = $null $superseded = $null; $declined = $null; $approved = $null; $arrival = $null if ($null -ne $Update) { $title = $Update.Title $kb = (@($Update.KnowledgebaseArticles) | ForEach-Object { 'KB' + $_ }) -join ', ' $class = $Update.UpdateClassificationTitle $products = (@($Update.ProductTitles)) -join ', ' $superseded = $Update.IsSuperseded $declined = $Update.IsDeclined $approved = $Update.IsApproved $arrival = $Update.ArrivalDate } [pscustomobject]@{ UpdateId = $Id Status = $Status Title = $title KB = $kb Classification = $class Products = $products IsSuperseded = $superseded IsDeclined = $declined IsApproved = $approved ArrivalDate = $arrival Message = $Message } } } process { if ($PSCmdlet.ParameterSetName -eq 'ById') { foreach ($item in $UpdateId) { $collectedIds.Add($item) } } } end { # Collect UpdateIDs from file if requested. if ($PSCmdlet.ParameterSetName -eq 'ByFile') { if (-not (Test-Path -LiteralPath $UpdateIdFilePath -PathType Leaf)) { throw "UpdateID file not found: $UpdateIdFilePath" } foreach ($line in (Get-Content -LiteralPath $UpdateIdFilePath)) { $trimmed = $line.Trim() if ($trimmed -and -not $trimmed.StartsWith('#')) { $collectedIds.Add($trimmed) } } } # Validate and de-duplicate GUIDs. $validIds = New-Object System.Collections.Generic.List[guid] $results = New-Object System.Collections.Generic.List[object] foreach ($raw in $collectedIds) { $parsed = [guid]::Empty if (-not [guid]::TryParse($raw, [ref]$parsed)) { $results.Add((New-ResultObject -Id $raw -Status 'InvalidId' -Update $null -Message 'Not a valid GUID.')) continue } if ($parsed -eq [guid]::Empty) { $results.Add((New-ResultObject -Id $raw -Status 'InvalidId' -Update $null -Message 'Placeholder GUID. Replace it with the UpdateID from the Microsoft Update Catalog.')) continue } if (-not $validIds.Contains($parsed)) { $validIds.Add($parsed) } } if ($DownloadedFilePath.Count -gt 0) { if ($validIds.Count -ne 1) { throw '-DownloadedFilePath can only be used when exactly one UpdateID is imported.' } foreach ($file in $DownloadedFilePath) { if (-not (Test-Path -LiteralPath $file -PathType Leaf)) { throw "File given in -DownloadedFilePath not found: $file" } } } if ($validIds.Count -gt 0) { # Load the WSUS administration module (installed with the WSUS console / role). try { Import-Module -Name UpdateServices -ErrorAction Stop } catch { throw "The UpdateServices module could not be loaded. Run the script on the WSUS server or on a computer with the WSUS administration console. $($_.Exception.Message)" } # Connect to WSUS. try { if ($PSBoundParameters.ContainsKey('WsusServer') -and $WsusServer) { if ($UseSsl) { $server = Get-WsusServer -Name $WsusServer -PortNumber $PortNumber -UseSsl } else { $server = Get-WsusServer -Name $WsusServer -PortNumber $PortNumber } } else { $server = Get-WsusServer } Write-Verbose ("Connected to WSUS server '{0}', port {1}." -f $server.Name, $server.PortNumber) } catch { throw "Connection to the WSUS server failed. $($_.Exception.Message)" } foreach ($id in $validIds) { $idText = $id.ToString() try { $existing = Get-WsusUpdateOrNull -Server $server -Id $id if ($null -ne $existing -and -not $Force) { $results.Add((New-ResultObject -Id $idText -Status 'AlreadyPresent' -Update $existing -Message 'Update already exists in WSUS. Use -Force to import again.')) continue } if (-not $PSCmdlet.ShouldProcess($idText, 'Import update from Microsoft Update Catalog into WSUS')) { $results.Add((New-ResultObject -Id $idText -Status 'Skipped' -Update $existing -Message 'WhatIf or declined confirmation.')) continue } Write-Verbose "Importing $idText ..." $server.ImportUpdateFromCatalogSite($idText, [string[]]$DownloadedFilePath) $imported = Get-WsusUpdateOrNull -Server $server -Id $id if ($null -eq $imported) { $results.Add((New-ResultObject -Id $idText -Status 'NotFoundAfterImport' -Update $null -Message 'Import returned without error, but GetUpdate does not find the update. Check SoftwareDistribution.log on the WSUS server.')) } else { $results.Add((New-ResultObject -Id $idText -Status 'Imported' -Update $imported -Message 'Verified with IUpdateServer.GetUpdate.')) } } catch { $results.Add((New-ResultObject -Id $idText -Status 'Failed' -Update $null -Message $_.Exception.Message)) } } } $results $problems = @($results | Where-Object { $_.Status -in @('Failed', 'InvalidId', 'NotFoundAfterImport') }) if ($problems.Count -gt 0) { Write-Warning ("{0} of {1} UpdateID(s) were not imported. See the Status and Message columns; import errors are logged in %ProgramFiles%\Update Services\LogFiles\SoftwareDistribution.log on the WSUS server." -f $problems.Count, $results.Count) exit 1 } }