Public/Export-IntuneAgentDiagnostic.ps1

function Export-IntuneAgentDiagnostic {
    <#
    .EXTERNALHELP IntuneScriptLab-Help.xml
    .SYNOPSIS
        Packs the agent's logs, registry state and timelines into one zip for a ticket.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType('IntuneScriptLab.Diagnostic')]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Path,

        [string]$LogPath,

        [switch]$SkipRegistry,

        [switch]$SkipTimeline,

        [switch]$Force
    )
    Write-Verbose "Starting $($MyInvocation.MyCommand.Name)"

    $packagePath = $Path
    if ([System.IO.Path]::GetExtension($packagePath) -ne '.zip') { $packagePath = "$packagePath.zip" }
    $zip = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($packagePath)
    if ((Test-Path -LiteralPath $zip) -and -not $Force) {
        $recordSplat = @{
            Message = "$zip exists; use -Force to overwrite it"
            ErrorId = 'DiagnosticPackageExists'
            Category = [System.Management.Automation.ErrorCategory]::ResourceExists
            TargetObject = $zip
            ExceptionType = [System.IO.IOException]
        }
        $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat))
    }
    if (-not $PSCmdlet.ShouldProcess($zip, 'Write the diagnostic package')) {
        return
    }
    $agentLogPath = $LogPath
    if (-not $agentLogPath) {
        $programData = if ($env:ProgramData) { $env:ProgramData } else { 'C:\ProgramData' }
        $agentLogPath = Join-Path -Path $programData -ChildPath 'Microsoft\IntuneManagementExtension\Logs'
    }
    $stagingName = "IntuneScriptLab-diag-$([guid]::NewGuid().ToString('N'))"
    $staging = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $stagingName
    $manifest = [System.Collections.Generic.List[string]]::new()

    try {
        $null = New-Item -ItemType Directory -Path $staging -Force @script:IslInternal

        # Logs
        $logFiles = @()
        $copiedCount = 0
        if (Test-Path -LiteralPath $agentLogPath -PathType Container) {
            $logFiles = @(Get-ChildItem -LiteralPath $agentLogPath -Filter '*.log' -File)
            $logFolder = Join-Path -Path $staging -ChildPath 'Logs'
            $null = New-Item -ItemType Directory -Path $logFolder -Force @script:IslInternal
            $notCopied = [System.Collections.Generic.List[string]]::new()
            foreach ($file in $logFiles) {
                $destination = Join-Path -Path $logFolder -ChildPath $file.Name
                try {
                    # A log the agent holds open is copied through a shared-read stream
                    Copy-IslSharedFile -Source $file.FullName -Destination $destination
                } catch {
                    # One log that cannot be read, or that rotated away since the folder was
                    # listed, is one item of the package: it is reported and the rest is written
                    $PSCmdlet.WriteError($_)
                    $notCopied.Add($file.Name)
                    continue
                }
                $copiedCount++
            }
            $manifest.Add("Logs: $copiedCount file(s) from $agentLogPath")
            if ($notCopied.Count) { $manifest.Add("Logs not copied: $($notCopied -join ', ')") }
        } else {
            $manifest.Add("Logs: folder not found: $agentLogPath")
            Write-Warning "Log folder not found: $agentLogPath"
        }

        # Device
        $system = [System.Collections.Generic.List[string]]::new()
        $system.Add("Computer: $env:COMPUTERNAME")
        $system.Add("Collected: $((Get-Date).ToString('o')) ($([System.TimeZoneInfo]::Local.Id))")
        $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
        if ($os) { $system.Add("Windows: $($os.Caption) $($os.Version) $($os.OSArchitecture)") }
        $system.Add("PowerShell: $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition))")
        $system.Add("Process architecture: $env:PROCESSOR_ARCHITECTURE")
        $module = $MyInvocation.MyCommand.Module
        if ($module) { $system.Add("IntuneScriptLab: $($module.Version)") }
        $service = Get-Service -Name IntuneManagementExtension -ErrorAction SilentlyContinue
        $system.Add("Agent service: $(if ($service) { $service.Status } else { 'not installed' })")
        $agentFolder = Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'Microsoft Intune Management Extension'
        $agentExe = Join-Path -Path $agentFolder -ChildPath 'Microsoft.Management.Services.IntuneWindowsAgent.exe'
        if ($agentExe -and (Test-Path -LiteralPath $agentExe)) {
            $system.Add("Agent version: $((Get-Item -LiteralPath $agentExe).VersionInfo.FileVersion)")
        }
        # The modules of this session, which decide what a harness run or an analysis loaded
        # (ERR-41). A folder under the user's Documents, which folder redirection can put on a
        # share named after the user, is written from <Documents>, and one under the profile from
        # %USERPROFILE%, so the list does not add the user's folder names to the package
        $system.Add('Loaded modules:')
        $userRoots = [ordered]@{
            '<Documents>' = [System.Environment]::GetFolderPath('MyDocuments')
            '%USERPROFILE%' = "$env:USERPROFILE"
        }
        foreach ($loadedModule in @(Get-Module | Sort-Object -Property Name, Version)) {
            $base = "$($loadedModule.ModuleBase)"
            foreach ($entry in $userRoots.GetEnumerator()) {
                $root = "$($entry.Value)".TrimEnd('\', '/')
                if (-not $root) {
                    continue
                }
                # The root itself, or a folder under it: C:\Users\bob.CONTOSO is not under C:\Users\bob
                $isRoot = $base.Equals($root, [System.StringComparison]::OrdinalIgnoreCase)
                $isUnder = $base.StartsWith("$root\", [System.StringComparison]::OrdinalIgnoreCase) -or
                $base.StartsWith("$root/", [System.StringComparison]::OrdinalIgnoreCase)
                if ($isRoot -or $isUnder) {
                    $base = $entry.Key + $base.Substring($root.Length)
                    break
                }
            }
            $system.Add(" $($loadedModule.Name) $($loadedModule.Version) $base")
        }
        Write-IslTextFile -Root $staging -RelativePath 'Device\system.txt' -Line $system
        if (Get-Command -Name dsregcmd.exe -ErrorAction SilentlyContinue) {
            $joinState = @(& dsregcmd.exe /status 2>&1 | ForEach-Object { "$_" })
            $sectionSplat = @{ Root = $staging; RelativePath = 'Device\dsregcmd.txt'; Line = $joinState }
            Write-IslTextFile @sectionSplat
            $manifest.Add('Device: system.txt, dsregcmd.txt')
        } else { $manifest.Add('Device: system.txt (dsregcmd not available)') }

        # Registry
        if (-not $SkipRegistry) {
            $keys = @(
                @{ Name = 'IntuneManagementExtension'; Depth = 6
                    Key = 'HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension'
                }
                @{ Name = 'Enrollments'; Key = 'HKLM:\SOFTWARE\Microsoft\Enrollments'; Depth = 2 }
                @{ Name = 'EnrollmentStatusTracking'; Depth = 6
                    Key = 'HKLM:\SOFTWARE\Microsoft\Windows\Autopilot\EnrollmentStatusTracking'
                }
                @{ Name = 'Autopilot'; Depth = 1
                    Key = 'HKLM:\SOFTWARE\Microsoft\Provisioning\Diagnostics\AutoPilot'
                }
            )
            foreach ($entry in $keys) {
                $lines = @(Get-IslRegistryText -Key $entry.Key -Depth $entry.Depth)
                $sectionSplat = @{ Root = $staging; RelativePath = "Registry\$($entry.Name).txt"; Line = $lines }
                Write-IslTextFile @sectionSplat
            }
            $manifest.Add("Registry: $(($keys | ForEach-Object { $_.Name }) -join ', ')")
        } else { $manifest.Add('Registry: skipped') }

        # Timeline
        if (-not $SkipTimeline -and $logFiles.Count) {
            $timelineFolder = Join-Path -Path $staging -ChildPath 'Timeline'
            $null = New-Item -ItemType Directory -Path $timelineFolder -Force @script:IslInternal
            $events = @(Get-IntuneAgentLog -Path $agentLogPath -Log All | Where-Object Event)
            $iso = @{ Name = 'Time'; Expression = { $_.Time.ToString('o') } }
            $eventRows = $events | Select-Object -Property $iso, Log, Event, Detail, Id, Message
            $csvSplat = @{ Encoding = 'UTF8' }
            if ($PSVersionTable.PSVersion -lt [version]'6.0') {
                # Windows PowerShell 5.1 writes a #TYPE line unless told not to; PowerShell 7.7 warns
                # that the switch is obsolete each time it is passed
                $csvSplat['NoTypeInformation'] = $true
            }
            $eventsCsv = Join-Path -Path $timelineFolder -ChildPath 'events.csv'
            $eventRows | Export-Csv -LiteralPath $eventsCsv @csvSplat @script:IslInternal
            $timelines = @(Get-IntuneAgentTimeline -Path $agentLogPath -Log All)
            $timelineRows = $timelines | Select-Object -Property Id, Name, Kind,
            @{ Name = 'Started'; Expression = { $_.Started.ToString('o') } },
            @{ Name = 'Ended'; Expression = { $_.Ended.ToString('o') } },
            @{ Name = 'Duration'; Expression = { $_.Duration.ToString() } }, Runs, Outcome, Summary
            $timelinesCsv = Join-Path -Path $timelineFolder -ChildPath 'timelines.csv'
            $timelineRows | Export-Csv -LiteralPath $timelinesCsv @csvSplat @script:IslInternal
            $manifest.Add("Timeline: $($events.Count) event(s), $($timelines.Count) timeline(s)")
        } else { $manifest.Add('Timeline: skipped') }

        $manifest.Insert(0, "IntuneScriptLab diagnostic package, $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))")
        Write-IslTextFile -Root $staging -RelativePath 'Manifest.txt' -Line $manifest

        if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -Force @script:IslInternal }
        $zipFolder = Split-Path -Path $zip -Parent
        if ($zipFolder -and -not (Test-Path -LiteralPath $zipFolder)) {
            $null = New-Item -ItemType Directory -Path $zipFolder -Force @script:IslInternal
        }
        $entryCount = Compress-IslFolder -Folder $staging -Destination $zip
    } catch {
        # Whatever failed, the package is not complete: the command ends without a result
        $PSCmdlet.ThrowTerminatingError($_)
    } finally {
        Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal
    }

    Write-Verbose "Completed $($MyInvocation.MyCommand.Name): $zip"
    [pscustomobject]@{
        PSTypeName = 'IntuneScriptLab.Diagnostic'
        Path = $zip
        Files = $entryCount
        Logs = $copiedCount
        Registry = -not $SkipRegistry
        Timeline = (-not $SkipTimeline) -and $logFiles.Count -gt 0
        SizeBytes = (Get-Item -LiteralPath $zip).Length
    }
}