### FILE: src/collect-autopatch-evidence.ps1 <# .SYNOPSIS Collects local MDM Update policy evidence used to validate Windows Autopatch remediation guidance. .DESCRIPTION This script pulls fast, actionable evidence from a device: - MDM policy application events from Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin filtered to Update/Policy related messages. - Effective update policy values from HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device\Update. - Optionally generates a Windows Update trace/log using Get-WindowsUpdateLog. It is intended to help administrators prove whether Autopatch report signals match the actual device-side effective policy state. .EXAMPLE PS C:\> .\collect-autopatch-evidence.ps1 -OutDir 'C:\Temp\AutopatchEvidence' -MaxEvents 50 -IncludeWindowsUpdateLog .EXAMPLE PS C:\> .\collect-autopatch-evidence.ps1 -OutDir 'C:\Temp\AutopatchEvidence' .NOTES Author: Souhaiel Morhag Company: MSEndpoint.com Blog: https://msendpoint.com Academy: https://app.msendpoint.com/academy LinkedIn: https://linkedin.com/in/souhaiel-morhag GitHub: https://github.com/Msendpoint License: MIT #> [CmdletBinding()] param( [Parameter(Mandition = $false)] [ValidateNotNullOrEmpty()] [string]$OutDir = 'C:\Temp\AutopatchEvidence', [Parameter(Mandition = $false)] [ValidateRange(1, 5000)] [int]$MaxEvents = 20, [Parameter(Mandition = $false)] [switch]$IncludeWindowsUpdateLog ) function Ensure-Directory { param([Parameter(Mandatory = $true)][string]$Path) if (-not (Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path -Force | Out-Null } } function Safe-GetItemProperty { param( [Parameter(Mandatory = $true)][string]$Path ) try { return Get-ItemProperty -Path $Path -ErrorAction Stop } catch { Write-Warning "Registry path not accessible or missing: $Path. $($_.Exception.Message)" return $null } } try { Ensure-Directory -Path $OutDir $timestamp = Get-Date -Format 'yyyyMMdd-HHmmss' $base = Join-Path -Path $OutDir -ChildPath $timestamp Ensure-Directory -Path $base $eventsPath = Join-Path $base 'mdm-policy-events.json' $regPath = Join-Path $base 'effective-update-policy.json' $summaryPath = Join-Path $base 'summary.txt' # 1) MDM policy events $filterPattern = 'Update|Policy' Write-Verbose "Collecting MDM events (LogName=Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin, MaxEvents=$MaxEvents)..." $events = Get-WinEvent -LogName 'Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin' -MaxEvents $MaxEvents -ErrorAction Stop | Where-Object { $_.Message -match $filterPattern } | Select-Object TimeCreated, Id, LevelDisplayName, Message $events | ConvertTo-Json -Depth 4 | Out-File -FilePath $eventsPath -Encoding UTF8 # 2) Effective Update policy hive $regHivePath = 'HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device\Update' Write-Verbose "Collecting effective update policy values from $regHivePath ..." $reg = Safe-GetItemProperty -Path $regHivePath # Keep this targeted: the article references a few common value families. $wantedProps = @( 'ExcludeWUDriversInQualityUpdate', 'ActiveHours', 'Defer', 'Pause', 'Restart' ) $effective = [ordered]@{} if ($null -ne $reg) { foreach ($p in $wantedProps) { if ($reg.PSObject.Properties.Name -contains $p) { $effective[$p] = $reg.$p } else { $effective[$p] = $null } } # Also include full property list for completeness but only if reasonably sized. $all = $reg.PSObject.Properties | Select-Object -Property Name, Value $effective['__allProperties'] = $all } $effective | ConvertTo-Json -Depth 8 | Out-File -FilePath $regPath -Encoding UTF8 # 3) Optional Windows Update trace if ($IncludeWindowsUpdateLog) { Write-Verbose 'Generating Windows Update log via Get-WindowsUpdateLog ...' try { # Put output under the same evidence folder. $logOut = Join-Path $base 'WindowsUpdate' Ensure-Directory -Path $logOut # Get-WindowsUpdateLog supports -LogPath in newer systems. # Use a robust approach: attempt with -LogPath, fall back if unavailable. try { $logFile = Join-Path $logOut ('Get-WindowsUpdateLog-{0}.log' -f $timestamp) Get-WindowsUpdateLog -LogPath $logOut -ErrorAction Stop | Out-Null # Get-WindowsUpdateLog may create a default file name; attempt to locate recent logs. # We'll add best-effort discovery. $created = Get-ChildItem -Path $logOut -Filter '*.log' -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($null -ne $created) { $logSummary = [ordered]@{ LogFolder = $logOut LatestLogFile = $created.FullName LastWriteTime = $created.LastWriteTime } } else { $logSummary = [ordered]@{ LogFolder = $logOut; LatestLogFile = $null } } } catch { # Fallback: invoke without -LogPath. Get-WindowsUpdateLog -ErrorAction Stop | Out-Null $logSummary = [ordered]@{ LogFolder = $logOut; LatestLogFile = $null } } $logSummary | ConvertTo-Json -Depth 4 | Out-File -FilePath (Join-Path $base 'windowsupdate-log-summary.json') -Encoding UTF8 } catch { Write-Warning "Failed to generate Windows Update log. $($_.Exception.Message)" } } # Summary $summary = [ordered]@{ ComputerName = $env:COMPUTERNAME CollectedAt = (Get-Date).ToString('o') MdmEventsCount = @($events).Count MdmEventsFile = $eventsPath EffectivePolicyFile = $regPath IncludeWindowsUpdateLog = $IncludeWindowsUpdateLog.IsPresent OutputFolder = $base } $summaryText = ($summary | Format-List | Out-String).Trim() $summaryText | Out-File -FilePath $summaryPath -Encoding UTF8 Write-Host "Evidence collection complete. Output: $base" return $base } catch { $err = $_ Write-Error "Autopatch evidence collection failed: $($err.Exception.Message)" throw } ### FILE: src/summarize-autopatch-evidence.ps1 <# .SYNOPSIS Summarizes collected Autopatch evidence (events + effective policy hive) into a compact report. .DESCRIPTION Reads the JSON files produced by collect-autopatch-evidence.ps1 and emits a human-friendly summary. This is useful for quickly validating whether Autopatch report guidance aligns with local device-side policy. .EXAMPLE PS C:\> .\summarize-autopatch-evidence.ps1 -EvidenceFolder 'C:\Temp\AutopatchEvidence\20260101-120000' .NOTES Author: Souhaiel Morhag Company: MSEndpoint.com Blog: https://msendpoint.com Academy: https://app.msendpoint.com/academy LinkedIn: https://linkedin.com/in/souhaiel-morhag GitHub: https://github.com/Msendpoint License: MIT #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$EvidenceFolder ) try { if (-not (Test-Path -LiteralPath $EvidenceFolder)) { throw "EvidenceFolder does not exist: $EvidenceFolder" } $eventsPath = Join-Path $EvidenceFolder 'mdm-policy-events.json' $regPath = Join-Path $EvidenceFolder 'effective-update-policy.json' if (-not (Test-Path -LiteralPath $eventsPath)) { throw "Missing file: $eventsPath" } if (-not (Test-Path -LiteralPath $regPath)) { throw "Missing file: $regPath" } $events = Get-Content -LiteralPath $eventsPath -Raw | ConvertFrom-Json $reg = Get-Content -LiteralPath $regPath -Raw | ConvertFrom-Json $latestEvent = $null if ($events) { $latestEvent = $events | Sort-Object TimeCreated -Descending | Select-Object -First 1 } $outLines = New-Object System.Collections.Generic.List[string] $outLines.Add("Computer: $env:COMPUTERNAME") $outLines.Add("EvidenceFolder: $EvidenceFolder") $outLines.Add("") $outLines.Add("MDM Policy Events") $outLines.Add("- Events captured: {0}" -f (@($events).Count)) if ($latestEvent) { $outLines.Add("- Latest: {0} | Id={1} | Level={2}" -f $latestEvent.TimeCreated, $latestEvent.Id, $latestEvent.LevelDisplayName) $outLines.Add("- Latest Message: {0}" -f ([string]$latestEvent.Message).Trim()) } $outLines.Add("") $outLines.Add("Effective Update Policy (HKLM\\SOFTWARE\\Microsoft\\PolicyManager\\current\\device\\Update)") foreach ($p in @('ExcludeWUDriversInQualityUpdate','ActiveHours','Defer','Pause','Restart')) { $val = $null # When converting from JSON, the property may be missing; handle gracefully. if ($reg.PSObject.Properties.Name -contains $p) { $val = $reg.$p } $outLines.Add("- $p: {0}" -f ($val | Out-String).Trim()) } $reportPath = Join-Path $EvidenceFolder 'autopatch-evidence-summary.txt' $outLines | Set-Content -LiteralPath $reportPath -Encoding UTF8 Write-Host "Summary written: $reportPath" return $reportPath } catch { Write-Error "Failed to summarize evidence: $($_.Exception.Message)" throw } ### FILE: index.php graphCall() and $_SESSION['ms_access_token']. $accessToken = $_SESSION['ms_access_token'] ?? null; // Example (disabled): // if ($accessToken) { // $endpoint = '/beta/deviceManagement/'; // $result = $ms->graphCall($endpoint, $accessToken, 'GET', null); // }