Private/ConvertTo-MgWindowsUpdatesRequestUri.ps1

function ConvertTo-MgWindowsUpdatesRequestUri {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [string] $Path,

        [Collections.IDictionary] $Query,

        [Parameter(Mandatory)]
        [uri] $GraphEndpoint
    )

    $endpoint = $GraphEndpoint.AbsoluteUri.TrimEnd('/')
    $isAbsolutePath = $Path -match '^https?://'
    if (-not $isAbsolutePath -and
        ($Path -match '\\' -or
         $Path -match '(?i)%2f|%5c|%2e' -or
         $Path -match '(?:^|/)\.{1,2}(?:/|$)' -or
         $Path -match '[?#]')) {
        throw "The Microsoft Graph request path '$Path' contains an unsafe path segment."
    }

    if ($isAbsolutePath) {
        $absolutePath = $null
        if (-not [uri]::TryCreate($Path, [UriKind]::Absolute, [ref] $absolutePath)) {
            throw "The Microsoft Graph request URI '$Path' is invalid."
        }
        if ($absolutePath.Scheme -ne $GraphEndpoint.Scheme -or
            $absolutePath.Authority -ne $GraphEndpoint.Authority) {
            throw (
                "The Microsoft Graph request host '$($absolutePath.Authority)' does not " +
                "match the active environment endpoint '$($GraphEndpoint.Authority)'."
            )
        }
        $uri = $absolutePath.AbsoluteUri
    }
    else {
        $normalizedPath = $Path.TrimStart('/')
        if ($normalizedPath -match '^(beta|v1\.0)/') {
            $uri = "$endpoint/$normalizedPath"
        }
        else {
            $uri = "$endpoint/beta/admin/windows/updates/$normalizedPath"
        }
    }

    $requestUri = [uri] $uri
    if ($requestUri.AbsolutePath -notmatch (
        '^/(?:beta/admin/windows/updates(?:/|$)|' +
        'v1\.0/deviceManagement/reports/exportJobs(?:/|$))'
    )) {
        throw "The Microsoft Graph request path '$($requestUri.AbsolutePath)' is not allowed."
    }

    if (-not $Query -or $Query.Count -eq 0) {
        return $uri
    }

    $pairs = @(
        foreach ($entry in $Query.GetEnumerator()) {
            if ($null -eq $entry.Value) {
                continue
            }

            $value = if ($entry.Value -is [array]) {
                $entry.Value -join ','
            }
            elseif ($entry.Value -is [bool] -or
                $entry.Value -is [Management.Automation.SwitchParameter]) {
                ([bool] $entry.Value).ToString().ToLowerInvariant()
            }
            else {
                [string] $entry.Value
            }

            '{0}={1}' -f $entry.Key, [Uri]::EscapeDataString($value)
        }
    )

    if ($pairs.Count -eq 0) {
        return $uri
    }

    $separator = if ($uri.Contains('?')) { '&' } else { '?' }
    return $uri + $separator + ($pairs -join '&')
}