Examples/Test-MgWindowsUpdatesTenant.ps1

[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [guid] $TenantId,

    [ValidateSet('Global', 'USGov', 'USGovDoD')]
    [string] $Environment = 'Global',

    [string] $OutputPath = (
        Join-Path $PWD 'MicrosoftGraphWindowsUpdates-TenantValidation.html'
    ),

    [switch] $ForceDeviceCode
)

$ErrorActionPreference = 'Stop'
$modulePath = Join-Path $PSScriptRoot '..\MicrosoftGraphWindowsUpdates.psd1'
$OutputPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($OutputPath)
$outputDirectory = [IO.Path]::GetDirectoryName($OutputPath)
if ($outputDirectory) {
    [void] (New-Item -ItemType Directory -Path $outputDirectory -Force)
}

Import-Module $modulePath -Force

$requiredScopes = @(
    'WindowsUpdates.Read.All'
    'DeviceManagementConfiguration.ReadWrite.All'
)
$tenantIdValue = $TenantId.ToString()
$context = Get-MgContext
$needsConnection = (
    -not $context -or
    $context.TenantId -ne $tenantIdValue -or
    $context.Environment -ne $Environment -or
    @($requiredScopes | Where-Object { $_ -notin $context.Scopes }).Count -gt 0
)

if ($needsConnection) {
    $connectParameters = @{
        Scopes = $requiredScopes
        ContextScope = 'Process'
        TenantId = $tenantIdValue
        Environment = $Environment
        NoWelcome = $true
    }
    if ($ForceDeviceCode) {
        $connectParameters.UseDeviceCode = $true
    }

    Connect-MgGraph @connectParameters
    $context = Get-MgContext
}

if (-not $context) {
    throw 'Microsoft Graph did not return an active context after authentication.'
}
if (-not $context.TenantId -or $context.TenantId -ne $tenantIdValue) {
    throw (
        "The active Microsoft Graph tenant '$($context.TenantId)' does not match " +
        "the requested tenant '$tenantIdValue'."
    )
}
if (-not $context.Environment -or $context.Environment -ne $Environment) {
    throw (
        "The active Microsoft Graph environment '$($context.Environment)' does not match " +
        "the requested environment '$Environment'."
    )
}
if ($context.AuthType -ne 'AppOnly') {
    $missingScopes = @(
        $requiredScopes | Where-Object { $_ -notin $context.Scopes }
    )
    if ($missingScopes.Count -gt 0) {
        throw (
            'The active Microsoft Graph session is missing required scope(s): ' +
            ($missingScopes -join ', ') + '.'
        )
    }
}

$records = [Collections.Generic.List[object]]::new()
$cache = @{}

function ConvertTo-ValidationExample {
    param([object] $InputObject)

    if ($null -eq $InputObject) {
        return ''
    }

    $json = $InputObject | ConvertTo-Json -Depth 7
    if ($json.Length -gt 5000) {
        return $json.Substring(0, 5000) + "`n... truncated"
    }

    $json
}

function Add-ValidationRecord {
    param(
        [string] $Command,
        [string] $Mode,
        [string] $Status,
        [string] $Invocation,
        [object[]] $Data = @(),
        [string] $Detail = ''
    )

    $items = @($Data)
    $example = if ($items.Count -gt 0) {
        ConvertTo-ValidationExample -InputObject $items[0]
    }
    else {
        ''
    }

    $records.Add([pscustomobject] @{
        Command = $Command
        Mode = $Mode
        Status = $Status
        Rows = $items.Count
        Invocation = $Invocation
        Example = $example
        Detail = $Detail
    })
}

function Invoke-ValidationRead {
    param(
        [string] $Command,
        [string] $Invocation,
        [scriptblock] $Action,
        [string] $CacheKey
    )

    if ($CacheKey) {
        $cache[$CacheKey] = [object[]] @()
    }

    try {
        $data = @(& $Action)
        Add-ValidationRecord `
            -Command $Command `
            -Mode 'Live tenant read' `
            -Status 'PASS' `
            -Invocation $Invocation `
            -Data $data
        if ($CacheKey) {
            $cache[$CacheKey] = $data
        }
        return $data
    }
    catch {
        Add-ValidationRecord `
            -Command $Command `
            -Mode 'Live tenant read' `
            -Status 'FAIL' `
            -Invocation $Invocation `
            -Detail $_.Exception.Message
        return @()
    }
}

function Add-ValidationSkip {
    param(
        [string] $Command,
        [string] $Invocation,
        [string] $Reason
    )

    Add-ValidationRecord `
        -Command $Command `
        -Mode 'Live tenant read' `
        -Status 'SKIP' `
        -Invocation $Invocation `
        -Detail $Reason
}

Add-ValidationRecord `
    -Command 'Connect-MgWindowsUpdatesBeta' `
    -Mode 'Authentication' `
    -Status 'SKIP' `
    -Invocation 'Connect-MgWindowsUpdatesBeta -IncludeIntuneReports' `
    -Data @([pscustomobject] @{
        TenantId = $context.TenantId
        Environment = $context.Environment
        AuthType = $context.AuthType
        Scopes = $context.Scopes
    }) `
    -Detail (
        'Not exercised. The harness authenticates with Connect-MgGraph once and reuses ' +
        'that process-scoped context for every validation command.'
    )

$topLevelReads = @(
    @{
        Command = 'Get-MgWindowsUpdateDeploymentBeta'
        Invocation = 'Get-MgWindowsUpdateDeploymentBeta -Top 2'
        CacheKey = 'Deployments'
        Action = { Get-MgWindowsUpdateDeploymentBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateDeploymentAudienceBeta'
        Invocation = 'Get-MgWindowsUpdateDeploymentAudienceBeta -Top 2'
        CacheKey = 'Audiences'
        Action = { Get-MgWindowsUpdateDeploymentAudienceBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateAssetBeta'
        Invocation = 'Get-MgWindowsUpdateAssetBeta -Top 2'
        CacheKey = 'Assets'
        Action = { Get-MgWindowsUpdateAssetBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateAzureAdDeviceBeta'
        Invocation = 'Get-MgWindowsUpdateAzureAdDeviceBeta -Top 2'
        CacheKey = 'Devices'
        Action = { Get-MgWindowsUpdateAzureAdDeviceBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateAssetGroupBeta'
        Invocation = 'Get-MgWindowsUpdateAssetGroupBeta -Top 2'
        CacheKey = 'AssetGroups'
        Action = { Get-MgWindowsUpdateAssetGroupBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdatePolicyBeta'
        Invocation = 'Get-MgWindowsUpdatePolicyBeta -Top 2'
        CacheKey = 'LegacyPolicies'
        Action = { Get-MgWindowsUpdatePolicyBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateAutopatchPolicyBeta'
        Invocation = 'Get-MgWindowsUpdateAutopatchPolicyBeta -Top 2'
        CacheKey = 'Policies'
        Action = { Get-MgWindowsUpdateAutopatchPolicyBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateCatalogEntryBeta'
        Invocation = 'Get-MgWindowsUpdateCatalogEntryBeta -Top 2'
        CacheKey = 'CatalogEntries'
        Action = { Get-MgWindowsUpdateCatalogEntryBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateTenantSettingBeta'
        Invocation = 'Get-MgWindowsUpdateTenantSettingBeta'
        CacheKey = 'TenantSetting'
        Action = { Get-MgWindowsUpdateTenantSettingBeta }
    }
    @{
        Command = 'Get-MgWindowsUpdateMdmAppSettingBeta'
        Invocation = 'Get-MgWindowsUpdateMdmAppSettingBeta'
        CacheKey = 'MdmAppSettings'
        Action = { Get-MgWindowsUpdateMdmAppSettingBeta }
    }
    @{
        Command = 'Get-MgWindowsUpdateDeviceProfileBeta'
        Invocation = 'Get-MgWindowsUpdateDeviceProfileBeta -Top 2'
        CacheKey = 'DeviceProfiles'
        Action = { Get-MgWindowsUpdateDeviceProfileBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdatePolicyAssignmentBeta'
        Invocation = 'Get-MgWindowsUpdatePolicyAssignmentBeta -Top 2'
        CacheKey = 'PolicyAssignments'
        Action = { Get-MgWindowsUpdatePolicyAssignmentBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateApplicableCatalogSummaryBeta'
        Invocation = 'Get-MgWindowsUpdateApplicableCatalogSummaryBeta -Top 2'
        CacheKey = 'CatalogSummaries'
        Action = { Get-MgWindowsUpdateApplicableCatalogSummaryBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateDriverReportBeta'
        Invocation = 'Get-MgWindowsUpdateDriverReportBeta -Top 2'
        CacheKey = 'DriverReports'
        Action = { Get-MgWindowsUpdateDriverReportBeta -Top 2 }
    }
    @{
        Command = 'Get-MgWindowsUpdateResourceConnectionBeta'
        Invocation = 'Get-MgWindowsUpdateResourceConnectionBeta'
        CacheKey = 'ResourceConnections'
        Action = { Get-MgWindowsUpdateResourceConnectionBeta }
    }
    @{
        Command = 'Get-MgWindowsUpdateOperationalInsightsConnectionBeta'
        Invocation = 'Get-MgWindowsUpdateOperationalInsightsConnectionBeta'
        CacheKey = 'OperationalInsightsConnections'
        Action = { Get-MgWindowsUpdateOperationalInsightsConnectionBeta }
    }
)

foreach ($read in $topLevelReads) {
    Invoke-ValidationRead @read | Out-Null
}

$types = @(Get-MgWindowsUpdateTypeBeta)
Add-ValidationRecord `
    -Command 'Get-MgWindowsUpdateTypeBeta' `
    -Mode 'Local model catalog' `
    -Status 'PASS' `
    -Invocation 'Get-MgWindowsUpdateTypeBeta' `
    -Data $types

$typedObject = New-MgWindowsUpdateObjectBeta `
    -TypeName dateDrivenRolloutSettings `
    -Property @{
        startDateTime = '2026-11-15T18:00:00Z'
        endDateTime = '2026-11-22T18:00:00Z'
    }
Add-ValidationRecord `
    -Command 'New-MgWindowsUpdateObjectBeta' `
    -Mode 'Local builder' `
    -Status 'PASS' `
    -Invocation 'New-MgWindowsUpdateObjectBeta -TypeName dateDrivenRolloutSettings' `
    -Data @($typedObject)

$filters = @(
    New-MgWindowsUpdateFilterBeta
    New-MgWindowsUpdateFilterBeta -Driver
    New-MgWindowsUpdateFilterBeta -Remediation
)
Add-ValidationRecord `
    -Command 'New-MgWindowsUpdateFilterBeta' `
    -Mode 'Local builder' `
    -Status 'PASS' `
    -Invocation 'New-MgWindowsUpdateFilterBeta; -Driver; -Remediation' `
    -Data $filters

$deployments = @($cache.Deployments)
if ($deployments.Count -gt 0) {
    $id = $deployments[0].id
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateDeploymentBeta (item)' `
        -Invocation "Get-MgWindowsUpdateDeploymentBeta -DeploymentId '$id'" `
        -Action { Get-MgWindowsUpdateDeploymentBeta -DeploymentId $id } |
        Out-Null
}

$audiences = @($cache.Audiences)
if ($audiences.Count -gt 0) {
    $id = $audiences[0].id
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateDeploymentAudienceMemberBeta' `
        -Invocation "Get-MgWindowsUpdateDeploymentAudienceMemberBeta -DeploymentAudienceId '$id'" `
        -Action {
            Get-MgWindowsUpdateDeploymentAudienceMemberBeta `
                -DeploymentAudienceId $id
        } |
        Out-Null
}
else {
    Add-ValidationSkip `
        -Command 'Get-MgWindowsUpdateDeploymentAudienceMemberBeta' `
        -Invocation 'Requires a deployment audience ID' `
        -Reason 'The tenant returned no deployment audiences.'
}

$assetGroups = @($cache.AssetGroups)
if ($assetGroups.Count -gt 0) {
    $id = $assetGroups[0].id
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateAssetGroupMemberBeta' `
        -Invocation "Get-MgWindowsUpdateAssetGroupMemberBeta -AssetGroupId '$id'" `
        -Action { Get-MgWindowsUpdateAssetGroupMemberBeta -AssetGroupId $id } |
        Out-Null
}
else {
    Add-ValidationSkip `
        -Command 'Get-MgWindowsUpdateAssetGroupMemberBeta' `
        -Invocation 'Requires an asset group ID' `
        -Reason 'The tenant returned no asset groups.'
}

$legacyPolicies = @($cache.LegacyPolicies)
if ($legacyPolicies.Count -gt 0) {
    $id = $legacyPolicies[0].id
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateComplianceChangeBeta' `
        -Invocation "Get-MgWindowsUpdateComplianceChangeBeta -UpdatePolicyId '$id' -Top 2" `
        -Action {
            Get-MgWindowsUpdateComplianceChangeBeta `
                -UpdatePolicyId $id `
                -Top 2
        } |
        Out-Null
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateContentApprovalBeta' `
        -Invocation "Get-MgWindowsUpdateContentApprovalBeta -UpdatePolicyId '$id' -Top 2" `
        -Action {
            Get-MgWindowsUpdateContentApprovalBeta `
                -UpdatePolicyId $id `
                -Top 2
        } |
        Out-Null
}
else {
    foreach ($command in @(
        'Get-MgWindowsUpdateComplianceChangeBeta'
        'Get-MgWindowsUpdateContentApprovalBeta'
    )) {
        Add-ValidationSkip `
            -Command $command `
            -Invocation 'Requires a legacy update policy ID' `
            -Reason 'The tenant returned no legacy update policies.'
    }
}

$policies = @($cache.Policies)
if ($policies.Count -gt 0) {
    $id = $policies[0].id
    $applicableCatalogs = @(
        Invoke-ValidationRead `
            -Command 'Get-MgWindowsUpdateApplicableCatalogBeta' `
            -Invocation "Get-MgWindowsUpdateApplicableCatalogBeta -PolicyId '$id' -Top 2" `
            -Action {
                Get-MgWindowsUpdateApplicableCatalogBeta -PolicyId $id -Top 2
            }
    )
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateApplicableContentBeta' `
        -Invocation "Get-MgWindowsUpdateApplicableContentBeta -PolicyId '$id' -Top 2" `
        -Action {
            Get-MgWindowsUpdateApplicableContentBeta -PolicyId $id -Top 2
        } |
        Out-Null
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdatePolicyApprovalBeta' `
        -Invocation "Get-MgWindowsUpdatePolicyApprovalBeta -PolicyId '$id' -Top 2" `
        -Action {
            Get-MgWindowsUpdatePolicyApprovalBeta -PolicyId $id -Top 2
        } |
        Out-Null
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateRingBeta' `
        -Invocation "Get-MgWindowsUpdateRingBeta -PolicyId '$id' -Top 2" `
        -Action { Get-MgWindowsUpdateRingBeta -PolicyId $id -Top 2 } |
        Out-Null

    if ($applicableCatalogs.Count -gt 0) {
        $catalogId = $applicableCatalogs[0].id
        Invoke-ValidationRead `
            -Command 'Get-MgWindowsUpdateApplicableCatalogDeviceBeta' `
            -Invocation (
                "Get-MgWindowsUpdateApplicableCatalogDeviceBeta " +
                "-PolicyId '$id' -ApplicableCatalogId '$catalogId' -Top 2"
            ) `
            -Action {
                Get-MgWindowsUpdateApplicableCatalogDeviceBeta `
                    -PolicyId $id `
                    -ApplicableCatalogId $catalogId `
                    -Top 2
            } |
            Out-Null
    }
    else {
        Add-ValidationSkip `
            -Command 'Get-MgWindowsUpdateApplicableCatalogDeviceBeta' `
            -Invocation 'Requires an applicable catalog ID' `
            -Reason 'The selected policy returned no applicable catalogs.'
    }
}
else {
    foreach ($command in @(
        'Get-MgWindowsUpdateApplicableCatalogBeta'
        'Get-MgWindowsUpdateApplicableCatalogDeviceBeta'
        'Get-MgWindowsUpdateApplicableContentBeta'
        'Get-MgWindowsUpdatePolicyApprovalBeta'
        'Get-MgWindowsUpdateRingBeta'
    )) {
        Add-ValidationSkip `
            -Command $command `
            -Invocation 'Requires a current policy ID' `
            -Reason 'The tenant returned no current policies.'
    }
}

$summaries = @($cache.CatalogSummaries)
if ($summaries.Count -gt 0) {
    $id = $summaries[0].id
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateAggregatedDeviceBeta' `
        -Invocation (
            "Get-MgWindowsUpdateAggregatedDeviceBeta " +
            "-ApplicableCatalogSummaryId '$id' -Top 2"
        ) `
        -Action {
            Get-MgWindowsUpdateAggregatedDeviceBeta `
                -ApplicableCatalogSummaryId $id `
                -Top 2
        } |
        Out-Null
}
else {
    Add-ValidationSkip `
        -Command 'Get-MgWindowsUpdateAggregatedDeviceBeta' `
        -Invocation 'Requires an applicability summary ID' `
        -Reason 'The tenant returned no applicability summaries.'
}

$driverReports = @($cache.DriverReports)
if ($driverReports.Count -gt 0) {
    $id = $driverReports[0].id
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateDriverDeviceStatusBeta' `
        -Invocation (
            "Get-MgWindowsUpdateDriverDeviceStatusBeta " +
            "-DriverUpdateReportId '$id' -Top 2"
        ) `
        -Action {
            Get-MgWindowsUpdateDriverDeviceStatusBeta `
                -DriverUpdateReportId $id `
                -Top 2
        } |
        Out-Null
}
else {
    Add-ValidationSkip `
        -Command 'Get-MgWindowsUpdateDriverDeviceStatusBeta' `
        -Invocation 'Requires a driver report ID' `
        -Reason 'The tenant returned no driver reports.'
}

$catalogEntries = @($cache.CatalogEntries)
if ($catalogEntries.Count -gt 0) {
    $catalogId = if ($catalogEntries[0].catalogId) {
        $catalogEntries[0].catalogId
    }
    else {
        $catalogEntries[0].id
    }
    $products = @(
        Invoke-ValidationRead `
            -Command 'Find-MgWindowsUpdateProductByCatalogIdBeta' `
            -Invocation (
                "Find-MgWindowsUpdateProductByCatalogIdBeta -CatalogId '$catalogId'"
            ) `
            -Action {
                Find-MgWindowsUpdateProductByCatalogIdBeta -CatalogId $catalogId
            }
    )
}
else {
    $products = @()
    Add-ValidationSkip `
        -Command 'Find-MgWindowsUpdateProductByCatalogIdBeta' `
        -Invocation 'Requires a catalog ID' `
        -Reason 'The tenant returned no catalog entries.'
}

$kbProducts = @(
    Invoke-ValidationRead `
        -Command 'Find-MgWindowsUpdateProductByKbNumberBeta' `
        -Invocation 'Find-MgWindowsUpdateProductByKbNumberBeta -KbNumber 5030213' `
        -Action { Find-MgWindowsUpdateProductByKbNumberBeta -KbNumber 5030213 }
)
$product = @($products + $kbProducts) | Select-Object -First 1
if ($product) {
    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateProductKnownIssueBeta' `
        -Invocation (
            "Get-MgWindowsUpdateProductKnownIssueBeta " +
            "-ProductId '$($product.id)' -DaysInPast 365 -IncludeAllActive"
        ) `
        -Action {
            Get-MgWindowsUpdateProductKnownIssueBeta `
                -ProductId $product.id `
                -DaysInPast 365 `
                -IncludeAllActive
        } |
        Out-Null
}
else {
    Add-ValidationSkip `
        -Command 'Get-MgWindowsUpdateProductKnownIssueBeta' `
        -Invocation 'Requires a product ID' `
        -Reason 'Product searches returned no products.'
}

Invoke-ValidationRead `
    -Command 'Get-MgWindowsUpdateQualityReport' `
    -Invocation 'Get-MgWindowsUpdateQualityReport' `
    -Action { Get-MgWindowsUpdateQualityReport } |
    Out-Null

try {
    $job = New-MgWindowsUpdateQualityReportExport -Confirm:$false
    Add-ValidationRecord `
        -Command 'New-MgWindowsUpdateQualityReportExport' `
        -Mode 'Live tenant report job' `
        -Status 'PASS' `
        -Invocation 'New-MgWindowsUpdateQualityReportExport -Confirm:$false' `
        -Data @($job)

    Invoke-ValidationRead `
        -Command 'Get-MgWindowsUpdateReportExport' `
        -Invocation "Get-MgWindowsUpdateReportExport -ExportJobId '$($job.id)'" `
        -Action { Get-MgWindowsUpdateReportExport -ExportJobId $job.id } |
        Out-Null

    $temporaryDirectory = Join-Path `
        ([IO.Path]::GetTempPath()) `
        "MicrosoftGraphWindowsUpdates-$([guid]::NewGuid())"
    $zipPath = Join-Path $temporaryDirectory 'validation.zip'
    try {
        $null = New-Item -ItemType Directory -Path $temporaryDirectory
        Save-MgWindowsUpdateReportExport `
            -ExportJobId $job.id `
            -Path $zipPath `
            -Confirm:$false |
            Out-Null
        Add-ValidationRecord `
            -Command 'Save-MgWindowsUpdateReportExport' `
            -Mode 'Live tenant report download' `
            -Status 'PASS' `
            -Invocation (
                "Save-MgWindowsUpdateReportExport -ExportJobId '$($job.id)' " +
                "-Path '<temporary>'"
            ) `
            -Data @([pscustomobject] @{ Downloaded = $true })
    }
    finally {
        Remove-Item `
            -LiteralPath $temporaryDirectory `
            -Recurse `
            -Force `
            -ErrorAction SilentlyContinue
    }
}
catch {
    foreach ($command in @(
        'New-MgWindowsUpdateQualityReportExport'
        'Get-MgWindowsUpdateReportExport'
        'Save-MgWindowsUpdateReportExport'
    )) {
        if ($records.Command -notcontains $command) {
            Add-ValidationRecord `
                -Command $command `
                -Mode 'Live tenant report job' `
                -Status 'FAIL' `
                -Invocation $command `
                -Detail $_.Exception.Message
        }
    }
}

$devices = @($cache.Devices)
$connections = @($cache.ResourceConnections)
$sampleId = if ($devices.Count -gt 0) {
    $devices[0].id
}
else {
    [guid]::Empty.ToString()
}
$samplePolicy = if ($policies.Count -gt 0) {
    $policies[0].id
}
else {
    [guid]::Empty.ToString()
}
$sampleLegacyPolicy = if ($legacyPolicies.Count -gt 0) {
    $legacyPolicies[0].id
}
else {
    [guid]::Empty.ToString()
}
$sampleAudience = if ($audiences.Count -gt 0) {
    $audiences[0].id
}
else {
    [guid]::Empty.ToString()
}
$sampleDeployment = if ($deployments.Count -gt 0) {
    $deployments[0].id
}
else {
    [guid]::Empty.ToString()
}
$sampleAssetGroup = if ($assetGroups.Count -gt 0) {
    $assetGroups[0].id
}
else {
    [guid]::Empty.ToString()
}
$sampleConnection = if ($connections.Count -gt 0) {
    $connections[0].id
}
else {
    [guid]::Empty.ToString()
}

$argumentValues = @{
    AssetGroupId = $sampleAssetGroup
    Asset = @(@{
        id = $sampleId
        '@odata.type' = '#microsoft.graph.windowsUpdates.azureADDevice'
    })
    Id = @($sampleId)
    Body = @{}
    UpdateCategory = 'quality'
    AssetId = $sampleId
    AzureAdDeviceId = $sampleId
    PolicyId = $samplePolicy
    UpdatePolicyId = $sampleLegacyPolicy
    ComplianceChangeId = [guid]::Empty.ToString()
    ContentApprovalId = [guid]::Empty.ToString()
    DeploymentAudienceId = $sampleAudience
    DeploymentId = $sampleDeployment
    OperationalInsightsConnectionId = $sampleConnection
    PolicyApprovalId = [guid]::Empty.ToString()
    RingId = [guid]::Empty.ToString()
    ResourceConnectionId = $sampleConnection
    MdmAppId = [guid]::Empty
    IsHotpatchEnabled = $false
    AzureSubscriptionId = [guid]::Empty
    AzureResourceGroupName = 'validation-resource-group'
    WorkspaceName = 'validation-workspace'
    MemberEntityType = '#microsoft.graph.windowsUpdates.azureADDevice'
}

$writeCommands = Get-Command -Module MicrosoftGraphWindowsUpdates |
    Where-Object {
        $_.Verb -in @(
            'New'
            'Set'
            'Remove'
            'Add'
            'Register'
            'Unregister'
            'Update'
        ) -and
        $_.Name -ne 'New-MgWindowsUpdateQualityReportExport'
    }

foreach ($command in $writeCommands) {
    $parameters = @{}
    foreach ($parameter in $command.ParameterSets[0].Parameters |
        Where-Object IsMandatory) {
        if ($argumentValues.ContainsKey($parameter.Name)) {
            $parameters[$parameter.Name] = $argumentValues[$parameter.Name]
        }
        else {
            $parameters[$parameter.Name] = 'validation'
        }
    }
    if ($command.Name -eq 'Update-MgWindowsUpdateDeploymentAudienceByIdBeta') {
        $parameters.AddMember = @($sampleId)
    }

    try {
        & $command @parameters -WhatIf -Confirm:$false | Out-Null
        $displayParameters = $parameters.GetEnumerator() |
            ForEach-Object { "-$($_.Key) <example>" }
        Add-ValidationRecord `
            -Command $command.Name `
            -Mode 'WhatIf write validation' `
            -Status 'PASS' `
            -Invocation (
                "$($command.Name) $($displayParameters -join ' ') -WhatIf"
            ) `
            -Detail 'No tenant mutation was sent.'
    }
    catch {
        Add-ValidationRecord `
            -Command $command.Name `
            -Mode 'WhatIf write validation' `
            -Status 'FAIL' `
            -Invocation "$($command.Name) -WhatIf" `
            -Detail $_.Exception.Message
    }
}

$encoder = [Net.WebUtility]
$rows = foreach ($record in $records | Sort-Object Command, Mode) {
    $content = $record.Example
    if ($record.Detail) {
        $content += "`n$($record.Detail)"
    }

    @"
<tr class="$($record.Status.ToLowerInvariant())">
  <td><code>$($encoder::HtmlEncode($record.Command))</code></td>
  <td>$($encoder::HtmlEncode($record.Mode))</td>
  <td><strong>$($record.Status)</strong></td>
  <td>$($record.Rows)</td>
  <td><code>$($encoder::HtmlEncode($record.Invocation))</code></td>
  <td><details><summary>Example / detail</summary><pre>$(
      $encoder::HtmlEncode($content)
  )</pre></details></td>
</tr>
"@

}

$passed = @($records | Where-Object Status -EQ 'PASS').Count
$failed = @($records | Where-Object Status -EQ 'FAIL').Count
$skipped = @($records | Where-Object Status -EQ 'SKIP').Count
$html = @"
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>MicrosoftGraphWindowsUpdates tenant validation</title>
  <style>
    body { font-family: Segoe UI, Arial; margin: 24px; color: #1f2937; }
    h1 { margin-bottom: 4px; }
    .summary { display: flex; gap: 12px; margin: 18px 0; }
    .card { border: 2px solid #1f2937; padding: 10px 16px;
      box-shadow: 4px 4px #d1d5db; }
    table { border-collapse: collapse; width: 100%; font-size: 13px; }
    th, td { border: 1px solid #9ca3af; padding: 8px; vertical-align: top; }
    th { background: #e5e7eb; position: sticky; top: 0; }
    .pass strong { color: #166534; }
    .fail strong { color: #b91c1c; }
    .skip strong { color: #92400e; }
    pre { white-space: pre-wrap; max-width: 760px; overflow: auto;
      background: #111827; color: #f9fafb; padding: 12px; }
    code { word-break: break-word; }
  </style>
</head>
<body>
  <h1>MicrosoftGraphWindowsUpdates tenant validation</h1>
  <p>Generated $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz'). Live reads use
  the available tenant. Writes use <code>-WhatIf</code>, except supported
  Intune report export jobs.</p>
  <div class="summary">
    <div class="card">PASS <b>$passed</b></div>
    <div class="card">FAIL <b>$failed</b></div>
    <div class="card">SKIP <b>$skipped</b></div>
    <div class="card">Records <b>$($records.Count)</b></div>
  </div>
  <table>
    <thead>
      <tr>
        <th>Command</th><th>Mode</th><th>Status</th><th>Rows</th>
        <th>Invocation</th><th>Actual sample</th>
      </tr>
    </thead>
    <tbody>
      $($rows -join "`n")
    </tbody>
  </table>
</body>
</html>
"@


Set-Content -LiteralPath $OutputPath -Value $html -Encoding utf8

[pscustomobject] @{
    OutputPath = (Resolve-Path $OutputPath).Path
    Passed = $passed
    Failed = $failed
    Skipped = $skipped
    Records = $records.Count
}

if ($failed -gt 0) {
    throw "$failed tenant validation call(s) failed. See $OutputPath."
}