Public/IntuneReports.ps1

function New-MgWindowsUpdateQualityReportExport {
    <#
    .SYNOPSIS
    Creates a Microsoft Graph export job for a supported Intune quality update report.
    .DESCRIPTION
    Creates a Microsoft Graph export job for a supported Intune quality update report. This command uses a supported Microsoft Graph v1.0 endpoint. Requires DeviceManagementConfiguration.ReadWrite.All in the active Microsoft Graph context.
    .PARAMETER Filter
    Specifies an OData $filter expression.
    .PARAMETER Format
    Specifies the report export format.
    .PARAMETER LocalizationType
    Specifies how localized report values are represented.
    .PARAMETER PolicyId
    Specifies the Microsoft Graph policy identifier.
    .PARAMETER ReportType
    Specifies the supported quality update report to export or retrieve.
    .PARAMETER Search
    Specifies the report search expression.
    .PARAMETER Select
    Specifies properties to include through OData $select.
    .PARAMETER SnapshotId
    Specifies a Microsoft Graph report snapshot identifier.
    .EXAMPLE
    PS> $job = New-MgWindowsUpdateQualityReportExport `
        -ReportType PolicyStatusSummary `
        -Format csv
    $job | Select-Object id,status
 
    Creates a policy-status summary export job and displays the job identifier and initial status for later polling or download.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [ValidateSet(
            'DeviceStatusByPolicy',
            'PolicyStatusSummary',
            'DeviceErrorsByPolicy'
        )]
        [string] $ReportType = 'PolicyStatusSummary',

        [guid] $PolicyId,

        [string] $Filter,

        [string[]] $Select,

        [ValidateSet('csv', 'json')]
        [string] $Format = 'csv',

        [ValidateSet(
            'replaceLocalizableValues',
            'localizedValuesAsAdditionalColumn'
        )]
        [string] $LocalizationType = 'replaceLocalizableValues',

        [string] $Search,

        [string] $SnapshotId
    )

    $definitions = @{
        DeviceStatusByPolicy = @{
            Name = 'QualityUpdateDeviceStatusByPolicy'
            RequiresPolicy = $true
            Select = @(
                'AADDeviceId',
                'AggregateState',
                'CurrentDeviceUpdateStatus',
                'CurrentDeviceUpdateSubstatus',
                'DeviceId',
                'DeviceName',
                'EventDateTimeUTC',
                'LastWUScanTimeUTC',
                'LatestAlertMessage',
                'OwnerType',
                'PolicyId',
                'UPN'
            )
        }
        PolicyStatusSummary = @{
            Name = 'QualityUpdatePolicyStatusSummary'
            RequiresPolicy = $false
            Select = @(
                'CountDevicesErrorStatus',
                'CountDevicesInProgressStatus',
                'CountDevicesSuccessStatus',
                'ExpediteQUReleaseDate',
                'PolicyId',
                'PolicyName'
            )
        }
        DeviceErrorsByPolicy = @{
            Name = 'QualityUpdateDeviceErrorsByPolicy'
            RequiresPolicy = $true
            Select = @(
                'AlertMessage',
                'DeviceId',
                'DeviceName',
                'ExpediteQUReleaseDate',
                'PolicyId',
                'UPN',
                'Win32ErrorCode'
            )
        }
    }

    $definition = $definitions[$ReportType]
    if ($definition.RequiresPolicy -and
        (-not $PSBoundParameters.ContainsKey('PolicyId') -or $PolicyId -eq [guid]::Empty)) {
        throw "-PolicyId is required by Microsoft Graph for report type '$ReportType'."
    }

    $policyFilter = if ($PolicyId -and $PolicyId -ne [guid]::Empty) {
        "PolicyId eq '$PolicyId'"
    }
    if ($Filter -and $policyFilter) {
        $Filter = "($policyFilter) and ($Filter)"
    }
    elseif ($policyFilter) {
        $Filter = $policyFilter
    }

    $body = @{
        '@odata.type' = '#microsoft.graph.deviceManagementExportJob'
        reportName = $definition.Name
        select = if ($Select) { $Select } else { $definition.Select }
        format = $Format
        localizationType = $LocalizationType
    }
    if ($Filter) {
        $body.filter = $Filter
    }
    if ($Search) {
        $body.search = $Search
    }
    if ($SnapshotId) {
        $body.snapshotId = $SnapshotId
    }

    if ($PSCmdlet.ShouldProcess($definition.Name, 'Create Microsoft Graph report export job')) {
        Invoke-MgWindowsUpdatesRequest `
            -Method POST `
            -Path '/v1.0/deviceManagement/reports/exportJobs' `
            -Body $body
    }
}

function Get-MgWindowsUpdateReportExport {
    <#
    .SYNOPSIS
    Gets one or more Microsoft Graph Intune report export jobs.
    .DESCRIPTION
    Gets one or more Microsoft Graph Intune report export jobs. This command uses a supported Microsoft Graph v1.0 endpoint. Requires DeviceManagementConfiguration.ReadWrite.All in the active Microsoft Graph context.
    .PARAMETER All
    Follows Microsoft Graph pagination links until all result pages are returned.
    .PARAMETER ExportJobId
    Specifies the Microsoft Graph report export job identifier.
    .EXAMPLE
    PS> $job = Get-MgWindowsUpdateReportExport -ExportJobId $exportJobId
    $job | Select-Object id,status,url
 
    Retrieves one report-export job and displays its current status and download URL.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern('^[A-Za-z0-9_-]+$')]
        [string] $ExportJobId,

        [switch] $All
    )

    $path = "/v1.0/deviceManagement/reports/exportJobs/$ExportJobId"

    Invoke-MgWindowsUpdatesRequest -Method GET -Path $path -All:$All
}

function Save-MgWindowsUpdateReportExport {
    <#
    .SYNOPSIS
    Waits for a Microsoft Graph report export job and saves its archive.
    .DESCRIPTION
    Waits for a Microsoft Graph report export job and saves its archive. This command uses a supported Microsoft Graph v1.0 endpoint. Requires DeviceManagementConfiguration.ReadWrite.All in the active Microsoft Graph context.
    .PARAMETER ExportJobId
    Specifies the Microsoft Graph report export job identifier.
    .PARAMETER Force
    Allows an existing destination file to be replaced atomically.
    .PARAMETER Path
    Specifies the destination archive path.
    .PARAMETER PollIntervalSeconds
    Specifies how often to poll the export job.
    .PARAMETER TimeoutSeconds
    Specifies the maximum time to wait for the export job.
    .EXAMPLE
    PS> Save-MgWindowsUpdateReportExport `
        -ExportJobId $exportJobId `
        -Path .\quality-update-report.zip
 
    Waits for the export job to complete and atomically saves its archive to the requested path.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [ValidatePattern('^[A-Za-z0-9_-]+$')]
        [string] $ExportJobId,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $Path,

        [ValidateRange(1, 300)]
        [int] $PollIntervalSeconds = 5,

        [ValidateRange(1, 3600)]
        [int] $TimeoutSeconds = 300,

        [switch] $Force
    )

    $resolvedPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
    if (Test-Path -LiteralPath $resolvedPath -PathType Container) {
        throw "The report export path '$resolvedPath' is a directory."
    }
    if ((Test-Path -LiteralPath $resolvedPath -PathType Leaf) -and -not $Force) {
        throw "The report export path '$resolvedPath' already exists. Use -Force to replace it."
    }

    if (-not $PSCmdlet.ShouldProcess(
        $resolvedPath,
        "Wait for and download Microsoft Graph report export $ExportJobId"
    )) {
        return
    }

    $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
    do {
        $job = Get-MgWindowsUpdateReportExport -ExportJobId $ExportJobId
        if ($job.status -eq 'failed') {
            throw "Microsoft Graph report export job '$ExportJobId' failed."
        }
        if ($job.status -eq 'completed') {
            break
        }
        if ((Get-Date) -ge $deadline) {
            throw "Microsoft Graph report export job '$ExportJobId' timed out."
        }
        Start-Sleep -Seconds $PollIntervalSeconds
    } while ($true)

    if (-not $job.url) {
        throw "Microsoft Graph report export job '$ExportJobId' completed without a download URL."
    }

    $partialPath = "$resolvedPath.$([guid]::NewGuid()).partial"
    try {
        Invoke-WebRequest -Uri $job.url -OutFile $partialPath -ErrorAction Stop
        if ($Force) {
            [IO.File]::Move($partialPath, $resolvedPath, $true)
        }
        else {
            [IO.File]::Move($partialPath, $resolvedPath)
        }
        Get-Item -LiteralPath $resolvedPath
    }
    finally {
        if (Test-Path -LiteralPath $partialPath) {
            Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
        }
    }
}

function Get-MgWindowsUpdateQualityReport {
    <#
    .SYNOPSIS
    Returns data from a supported Microsoft Graph Intune quality update report.
    .DESCRIPTION
    Returns data from a supported Microsoft Graph Intune quality update report. This command uses a supported Microsoft Graph v1.0 endpoint. Requires DeviceManagementConfiguration.ReadWrite.All in the active Microsoft Graph context.
    .PARAMETER Filter
    Specifies an OData $filter expression.
    .PARAMETER PolicyId
    Specifies the Microsoft Graph policy identifier.
    .PARAMETER PollIntervalSeconds
    Specifies how often to poll the export job.
    .PARAMETER ReportType
    Specifies the supported quality update report to export or retrieve.
    .PARAMETER Search
    Specifies the report search expression.
    .PARAMETER Select
    Specifies properties to include through OData $select.
    .PARAMETER SnapshotId
    Specifies a Microsoft Graph report snapshot identifier.
    .PARAMETER TimeoutSeconds
    Specifies the maximum time to wait for the export job.
    .EXAMPLE
    PS> $rows = Get-MgWindowsUpdateQualityReport `
        -ReportType PolicyStatusSummary
    $rows | Select-Object PolicyName,CountDevicesSuccessStatus,CountDevicesErrorStatus
 
    Retrieves the supported policy-status report as PowerShell objects and selects the most useful status columns.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [ValidateSet(
            'DeviceStatusByPolicy',
            'PolicyStatusSummary',
            'DeviceErrorsByPolicy'
        )]
        [string] $ReportType = 'PolicyStatusSummary',

        [guid] $PolicyId,

        [string] $Filter,

        [string[]] $Select,

        [string] $Search,

        [string] $SnapshotId,

        [ValidateRange(1, 300)]
        [int] $PollIntervalSeconds = 5,

        [ValidateRange(1, 3600)]
        [int] $TimeoutSeconds = 300
    )

    if (-not $PSCmdlet.ShouldProcess($ReportType, 'Retrieve Microsoft Graph quality update report')) {
        return
    }

    if ($ReportType -in 'DeviceStatusByPolicy', 'DeviceErrorsByPolicy' -and
        (-not $PSBoundParameters.ContainsKey('PolicyId') -or $PolicyId -eq [guid]::Empty)) {
        $summaryRows = @(
            Get-MgWindowsUpdateQualityReport `
                -ReportType PolicyStatusSummary `
                -PollIntervalSeconds $PollIntervalSeconds `
                -TimeoutSeconds $TimeoutSeconds
        )
        $policyIds = @(
            $summaryRows |
                ForEach-Object { $_.PolicyId } |
                Where-Object { $_ } |
                Sort-Object -Unique
        )

        foreach ($currentPolicyId in $policyIds) {
            $reportParameters = @{
                ReportType = $ReportType
                PolicyId = [guid] $currentPolicyId
                PollIntervalSeconds = $PollIntervalSeconds
                TimeoutSeconds = $TimeoutSeconds
            }
            foreach ($parameterName in 'Filter', 'Select', 'Search', 'SnapshotId') {
                if ($PSBoundParameters.ContainsKey($parameterName)) {
                    $reportParameters[$parameterName] = $PSBoundParameters[$parameterName]
                }
            }
            Get-MgWindowsUpdateQualityReport @reportParameters
        }
        return
    }

    $exportParameters = @{
        ReportType = $ReportType
        Format = 'csv'
        Confirm = $false
    }
    foreach ($parameterName in 'PolicyId', 'Filter', 'Select', 'Search', 'SnapshotId') {
        if ($PSBoundParameters.ContainsKey($parameterName)) {
            $exportParameters[$parameterName] = $PSBoundParameters[$parameterName]
        }
    }

    $temporaryDirectory = Join-Path `
        ([System.IO.Path]::GetTempPath()) `
        "MicrosoftGraphWindowsUpdates-$([guid]::NewGuid())"
    $archivePath = Join-Path $temporaryDirectory 'report.zip'
    $expandedPath = Join-Path $temporaryDirectory 'report'

    try {
        $null = New-Item -ItemType Directory -Path $temporaryDirectory -Force
        $job = New-MgWindowsUpdateQualityReportExport @exportParameters
        if (-not $job.id) {
            throw 'Microsoft Graph created the export job without returning an ID.'
        }
        Save-MgWindowsUpdateReportExport `
            -ExportJobId $job.id `
            -Path $archivePath `
            -PollIntervalSeconds $PollIntervalSeconds `
            -TimeoutSeconds $TimeoutSeconds `
            -Confirm:$false |
            Out-Null

        Expand-Archive -LiteralPath $archivePath -DestinationPath $expandedPath -Force
        $reportFiles = @(
            Get-ChildItem `
                -LiteralPath $expandedPath `
                -Filter '*.csv' `
                -File `
                -Recurse
        )
        if ($reportFiles.Count -eq 0) {
            throw "Microsoft Graph report export job '$($job.id)' contained no CSV report."
        }

        foreach ($reportFile in $reportFiles) {
            Import-Csv -LiteralPath $reportFile.FullName
        }
    }
    finally {
        if (Test-Path -LiteralPath $temporaryDirectory) {
            try {
                Remove-Item -LiteralPath $temporaryDirectory -Recurse -Force -ErrorAction Stop
            }
            catch {
                Write-Warning "Unable to remove temporary report data at '$temporaryDirectory': $_"
            }
        }
    }
}