Public/Export-AutopilotDevicePreparationDiagnostic.ps1

function Export-AutopilotDevicePreparationDiagnostic {
    <#
    .SYNOPSIS
        Writes an Autopilot device preparation diagnostic report to JSON.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Path,

        [ValidateRange(1, 5000)]
        [int]$EventLogLimit = 200,

        [datetime]$Since = (Get-Date).AddDays(-7),

        [switch]$IncludeEventMessage,

        [switch]$IncludeMdmDiagnostics,

        [switch]$Force
    )

    $resolvedPath = [Environment]::ExpandEnvironmentVariables($Path)
    if ([string]::IsNullOrWhiteSpace($resolvedPath)) {
        throw 'Path must not be empty or whitespace.'
    }

    if ($resolvedPath.EndsWith([IO.Path]::DirectorySeparatorChar.ToString()) -or
        $resolvedPath.EndsWith([IO.Path]::AltDirectorySeparatorChar.ToString())) {
        throw "Path must include a report file name: $Path"
    }

    if ([IO.Path]::GetExtension($resolvedPath) -ne '.json') {
        $resolvedPath = "$resolvedPath.json"
    }

    $directory = Split-Path -Path $resolvedPath -Parent
    if ([string]::IsNullOrWhiteSpace($directory)) {
        $directory = (Get-Location).Path
        $resolvedPath = Join-Path -Path $directory -ChildPath $resolvedPath
    }

    if (-not (Test-Path -LiteralPath $directory)) {
        if ($PSCmdlet.ShouldProcess($directory, 'Create diagnostic report directory')) {
            [IO.Directory]::CreateDirectory($directory) | Out-Null
        } else {
            return
        }
    }

    if ((Test-Path -LiteralPath $resolvedPath) -and -not $Force) {
        throw "The report already exists: $resolvedPath. Use -Force to replace it."
    }

    $report = Get-AutopilotDevicePreparationDiagnostic -EventLogLimit $EventLogLimit -Since $Since -IncludeEventMessage:$IncludeEventMessage
    if ($PSCmdlet.ShouldProcess($resolvedPath, 'Write diagnostic JSON report')) {
        $report | ConvertTo-Json -Depth 8 | Out-File -LiteralPath $resolvedPath -Encoding utf8 -Force
    } else {
        return
    }

    if ($IncludeMdmDiagnostics) {
        $diagnosticTool = Join-Path -Path $env:WINDIR -ChildPath 'System32\MdmDiagnosticsTool.exe'
        $zipPath = Join-Path -Path $directory -ChildPath (([IO.Path]::GetFileNameWithoutExtension($resolvedPath)) + '.mdm.zip')
        if (-not (Test-Path -LiteralPath $diagnosticTool)) {
            throw "MdmDiagnosticsTool.exe was not found at $diagnosticTool."
        }
        if ($PSCmdlet.ShouldProcess($zipPath, 'Collect MDM, device provisioning, and Autopilot logs')) {
            & $diagnosticTool -area 'DeviceEnrollment;DeviceProvisioning;Autopilot' -zip $zipPath
            if ($LASTEXITCODE -ne 0) {
                throw "MdmDiagnosticsTool.exe failed with exit code $LASTEXITCODE."
            }
        }
    }

    Get-Item -LiteralPath $resolvedPath
}