Private/GetUpdateIDFromKB.ps1

function GetUpdateIDFromKB {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]
        $KB,

        [Parameter()]
        [string[]]
        $Filter
    )

    try {
        $additionalFilters = ""

        if ($Filter) {
            $additionalFilters = [System.Net.WebUtility]::UrlEncode(" $( [string]::Join(" ", $Filter) )")
        }

        $finalUri = "https://www.catalog.update.microsoft.com/Search.aspx?q=$KB${additionalFilters}"
        Write-Verbose "Searching for UpdateID from KB `"$KB`" using `"$finalUri`" as the final URI..."
        $webRequestParams = GetWebRequestSplatBase -Uri $finalUri
        $response = Invoke-WebRequest @webRequestParams -ErrorAction Stop
        $updateLinks = $response.Links | Where-Object -Property "onclick" -Like "*goToDetail*"

        if (!$updateLinks) {
            Write-Error -Message "No updates found matching KB $KB." `
                -Category ObjectNotFound `
                -ErrorId "NoUpdatesFound" `
                -TargetObject $KB
            return $null
        }

        if ($updateLinks.Count -gt 1) {
            if ($Filter) {
                $filtersUsed = "(filters used: $( [string]::Join(", ", $Filter) ))"
            } else {
                $filtersUsed = "(no additional filters used)"
            }

            Write-Error -Message "Found several matching updates when searching for the update with KB `"${KB}`" ${filtersUsed}." `
                -Category ObjectNotFound `
                -ErrorId "MultipleUpdatesFound" `
                -TargetObject $KB
            return $null
        }

        # At this point updateLinks has been unrolled to be its single result and not an array
        if ($updateLinks.id -notmatch ".*([a-zA-Z\d]{8}-(?:[a-zA-Z\d]{4}-){3}[a-zA-Z\d]{12}).*") {
            Write-Error -Message "Couldn't extract UpdateID from HTML id of update `"$($updateLinks.id)`"." `
                -Category InvalidData `
                -ErrorId "FailedExtractingUpdateID" `
                -TargetObject $updateLinks.id
            return $null
        }

        return $Matches[1]
    } catch {
        throw
    }
}

# Copyright (c) 2023 AJ Tek Corporation. All Rights Reserved.