39 production-tested scripts for Intune, Entra ID, Exchange Online and Windows — detection & remediation pairs, Graph automations and reporting tools. Every script links to the full guide that explains when (and when not) to run it.
Automated PowerShell script utilizing Microsoft Graph v2 SDK to audit endpoint compliance states, hardware metrics, and synchronization health across Microsoft Intune fleets.
A PowerShell and M365 SaaS toolkit to discover EWS-dependent applications, correlate audit logs against Entra ID app registrations, manage EwsAllowedAppIDs containment, and execute a phased mailbox-level EWS cutover ahead of the October 2026 retirement.
PowerShell toolkit and SaaS dashboard to baseline Copilot Pages usage, identify licensed users, and track adoption readiness ahead of the September 2026 'Edit in Pages' UX change (MC1466760).
### FILE: scripts/Get-CopilotPagesUsageBaseline.ps1
<#
.SYNOPSIS
Baselines Microsoft 365 Copilot Pages activity from the Unified Audit Log before the MC1466760 UX cutover.
.DESCRIPTION
Connects to Exchange Online and queries the Unified Audit Log for CopilotInteraction records with
PageCreated and PageEdited operations over the last 30 days. Results are paginated using session-based
ReturnLargeSet retrieval to handle large tenants, then exported to CSV for use as a pre-cutover usage
baseline. This baseline helps identify which users are actively creating/editing Copilot Pages so that
proactive change-management communications can be targeted ahead of the September 2026 GA rollout
(Message Center post MC1466760), which removes the 'browse existing Pages' capability from the
'Edit in Pages' menu and moves it to the Library tab and the '/' slash-command menu.
.EXAMPLE
.\Get-CopilotPagesUsageBaseline.ps1
Connects to Exchange Online (interactive), pulls the last 30 days of Copilot Pages activity, and exports
the results to .\CopilotPagesActivity_Baseline.csv
.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
Required Scopes / Roles:
- AuditLog.Read.All (Microsoft Graph, if used elsewhere)
- View-Only Audit Logs (Exchange Online RBAC role)
Requires:
- ExchangeOnlineManagement module (Install-Module ExchangeOnlineManagement)
Run this BEFORE the September 2026 cutover date referenced in MC1466760 to capture a clean baseline.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[int]$LookbackDays = 30,
[Parameter(Mandatory = $false)]
[string]$OutputPath = ".\CopilotPagesActivity_Baseline.csv"
)
#region Connect
try {
Write-Verbose "Connecting to Exchange Online..."
Connect-ExchangeOnline -ErrorAction Stop
}
catch {
Write-Error "Failed to connect to Exchange Online: $($_.Exception.Message)"
exit 1
}
#endregion
#region Baseline audit pull - last N days of Page activity
$startDate = (Get-Date).AddDays(-$LookbackDays)
$endDate = Get-Date
$results = @()
$sessionId = "CopilotPagesAudit-$(Get-Date -Format yyyyMMddHHmm)"
try {
Write-Output "Querying Unified Audit Log for CopilotInteraction (PageCreated / PageEdited) from $startDate to $endDate..."
do {
$batch = Search-UnifiedAuditLog `
-StartDate $startDate `
-EndDate $endDate `
-RecordType CopilotInteraction `
-Operations "PageCreated", "PageEdited" `
-SessionId $sessionId `
-SessionCommand ReturnLargeSet `
-ResultSize 5000 `
-ErrorAction Stop
if ($batch) { $results += $batch }
} while ($batch.Count -eq 5000)
if ($results.Count -eq 0) {
Write-Warning "No CopilotInteraction PageCreated/PageEdited events found in the specified date range."
}
$results |
Select-Object CreationDate, UserIds, Operations, AuditData |
Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8
Write-Output "Exported $($results.Count) Copilot Pages events to $OutputPath"
exit 0
}
catch {
Write-Error "Audit pull failed: $($_.Exception.Message)"
exit 1
}
finally {
Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
}
#endregion
### FILE: scripts/Get-CopilotLicensedUsersForComms.ps1
<#
.SYNOPSIS
Enumerates Microsoft 365 users licensed for Copilot to scope a targeted change-management comms list.
.DESCRIPTION
Connects to Microsoft Graph (v2 SDK) and retrieves all users, filtering to those assigned a Microsoft 365
Copilot or Copilot Chat license SKU. Produces a CSV of DisplayName / UserPrincipalName suitable for driving
a targeted email or Teams announcement ahead of the MC1466760 'Edit in Pages' UX change rolling out GA
worldwide in September 2026. This script performs read-only enumeration; no licenses, policies, or
configuration are modified.
.EXAMPLE
.\Get-CopilotLicensedUsersForComms.ps1
Connects to Microsoft Graph interactively and exports Copilot-licensed users to
.\CopilotLicensedUsers_ForComms.csv
.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
Required Scopes:
- User.Read.All
- Organization.Read.All
Requires:
- Microsoft.Graph PowerShell SDK v2 (Install-Module Microsoft.Graph)
- Do NOT use the deprecated AzureAD / MSOnline modules.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string[]]$CopilotSkuNames = @("Microsoft_365_Copilot", "Copilot_Chat"),
[Parameter(Mandatory = $false)]
[string]$OutputPath = ".\CopilotLicensedUsers_ForComms.csv"
)
#region Connect via Microsoft.Graph v2
try {
Write-Verbose "Connecting to Microsoft Graph..."
Connect-MgGraph -Scopes "User.Read.All", "Organization.Read.All" -NoWelcome -ErrorAction Stop
}
catch {
Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
exit 1
}
PowerShellMicrosoft Teams PowerShell ModuleMicrosoft GraphPHP
Teams Copilot Chat Governance Toolkit for GCC, GCC High & DoD
PowerShell audit tooling and a Microsoft 365 SaaS Engine dashboard for tracking and controlling Teams Copilot Chat rollout compliance across US Government cloud instances (GCC, GCC High, DoD).
### FILE: scripts/Audit-CopilotChatEnablement.ps1
<#
.SYNOPSIS
Cross-cloud audit of Microsoft Teams Copilot Chat enablement signals across GCC, GCC High, and DoD tenants.
.DESCRIPTION
This script connects to a specified US Government Community Cloud instance (GCC, GCC High, or DoD)
using the MicrosoftTeams PowerShell module and enumerates all Teams Messaging Policies and Meeting
Policies to determine the current enablement state of Copilot Chat surfaces (1:1/Group Chat, Channels,
Calls, Meetings).
Because Teams PowerShell sessions are cloud-instance-specific and credentials do not roam across
sovereign cloud boundaries, this script must be run once per cloud instance connection by an admin
holding the appropriate role in that tenant.
The report flags policies where transcription-dependent Copilot features (Calls/Meetings recap) may
be blocked due to 'AllowTranscription' being disabled at the tenant or policy level -- a common
inherited default in DoD-adjacent CMMC/NIST 800-171 hardening baselines.
IMPORTANT: Property names such as AllowCopilotChat and AllowChannelSummary reflect the schema at
time of writing (Sep 2026) and are subject to change post-GA. Always validate against:
Get-CsTeamsMessagingPolicy | Get-Member -MemberType Property
before relying on this script's output in a compliance report.
.EXAMPLE
.\Audit-CopilotChatEnablement.ps1 -CloudInstance GCCHigh -TenantAdminUPN admin@contoso.us
Connects to the GCC High cloud instance as admin@contoso.us and exports a CSV audit report to the
default C:\Reports path.
.EXAMPLE
.\Audit-CopilotChatEnablement.ps1 -CloudInstance DoD -TenantAdminUPN admin@contoso.mil -ReportPath 'D:\Audits\dod_copilot_audit.csv'
Connects to the DoD cloud instance and writes the report to a custom path.
.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)]
[ValidateSet('GCC','GCCHigh','DoD')]
[string]$CloudInstance,
[Parameter(Mandatory = $true)]
[string]$TenantAdminUPN,
[Parameter(Mandatory = $false)]
[string]$ReportPath = "C:\Reports\CopilotChat_Audit_$(Get-Date -Format 'yyyyMMdd_HHmm').csv"
)
$ErrorActionPreference = 'Stop'
$results = [System.Collections.Generic.List[Object]]::new()
# Map cloud instance to the correct Teams PowerShell admin endpoint (reference only —
# actual connection is handled via TeamsEnvironmentName below)
$cloudEndpointMap = @{
'GCC' = 'https://admin.teams.microsoft.com'
'GCCHigh' = 'https://admin.teams.microsoft.us'
'DoD' = 'https://admin.teams.microsoft.us'
}
try {
# Ensure the report directory exists before we attempt to write to it
$reportDir = Split-Path -Path $ReportPath -Parent
if ($reportDir -and -not (Test-Path -Path $reportDir)) {
New-Item -Path $reportDir -ItemType Directory -Force | Out-Null
}
Write-Host "[+] Connecting to Teams PowerShell — Cloud Instance: $CloudInstance ($($cloudEndpointMap[$CloudInstance]))" -ForegroundColor Cyan
$connectParams = @{
AccountId = $TenantAdminUPN
}
# GCC uses the standard commercial cloud endpoint implicitly; GCC High and DoD require
# explicit environment targeting so the module authenticates against the correct boundary
switch ($CloudInstance) {
'GCCHigh' { $connectParams['TeamsEnvironmentName'] = 'TeamsGCCH' }
'DoD' { $connectParams['TeamsEnvironmentName'] = 'TeamsDOD' }
}
Connect-MicrosoftTeams @connectParams
Write-Host "[+] Connected. Enumerating messaging and meeting policies..." -ForegroundColor Cyan
# Pull ALL messaging policies — Copilot Chat surface toggle lives here in current builds
$messagingPolicies = Get-CsTeamsMessagingPolicy
foreach ($policy in $messagingPolicies) {
# Property names below reflect current (Sep 2026) schema; validate against
# Get-CsTeamsMessagingPolicy | Get-Member if Microsoft renames properties post-GA
$copilotChatEnabled = $policy.AllowCopilotChat -as [bool]
$channelSummaryEnabled = $policy.AllowChannelSummary -as [bool]
$results.Add([PSCustomObject]@{
CloudInstance = $CloudInstance
RecordType = 'MessagingPolicy'
PolicyName = $policy.Identity
AllowCopilotChat = $copilotChatEnabled
AllowChannelSummary = $channelSummaryEnabled
IsGlobalPolicy = ($policy.Identity -eq 'Global')
AllowTranscription = $null
AllowCloudRecording = $null
CopilotDependencyMet = $null
AuditTimestamp = (Get-Date).ToString('o')
})
}
# Cross-reference meeting policies for the transcription dependency gate — Calls and
# Meetings Copilot recap features require AllowTranscription to be $true
$meetingPolicies = Get-CsTeamsMeetingPolicy
foreach ($mp in $meetingPolicies) {
$results.Add([PSCustomObject]@{
CloudInstance = $CloudInstance
RecordType = 'MeetingPolicy'
PolicyName = $mp.Identity
AllowCopilotChat = $null
AllowChannelSummary = $null
IsGlobalPolicy = ($mp.Identity -eq 'Global')
AllowTranscription = $mp.AllowTranscription -as [bool]
AllowCloudRecording = $mp.AllowCloudRecording -as [bool]
CopilotDependencyMet = ($mp.AllowTranscription -eq $true)
AuditTimestamp = (Get-Date).ToString('o')
})
}
<#
.SYNOPSIS
Audits Intune-managed devices for compliance with security baselines.
.DESCRIPTION
This script retrieves a list of devices managed by Intune and checks their compliance status
by fetching the associated mobile app policy for each device. Ideal for regular compliance checks.
.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
.EXAMPLE
.\Audit-IntuneCompliance.ps1
#>
[CmdletBinding()]
param ()
try {
# Retrieve all Intune managed devices
$devices = Get-IntuneManagedDevice
# Check compliance for each device
foreach ($device in $devices) {
# Fetch mobile app policy for the current device
$compliancePolicy = Get-IntuneMobileAppPolicy -DeviceId $device.Id
Write-Output "Device ID: $($device.Id), Compliance Status: $($compliancePolicy.Status)"
}
} catch {
Write-Error "An error occurred: $_"
}
Outlook Hyperlink Warning Remediation and Trusted Sites Configuration via Intune
Detects and remediates Outlook and Office hyperlink security warnings while configuring trusted sites in the Internet Zone registry via Intune Proactive Remediation scripts.
Monitor Sensitivity Label Policy Sync Status in Microsoft Purview
Connects to Security & Compliance PowerShell and reports the distribution/sync status of all sensitivity label publishing policies, highlighting any that are not yet fully propagated.
<#
.SYNOPSIS
Monitors and reports the sync/distribution status of all sensitivity label publishing policies in Microsoft Purview.
.DESCRIPTION
This script connects to the Security & Compliance PowerShell endpoint using the
ExchangeOnlineManagement module and retrieves all sensitivity label publishing policies
along with their DistributionStatus property.
It is designed to help Microsoft Purview / Information Protection administrators:
- Confirm that policy changes have fully propagated across Microsoft 365 infrastructure.
- Identify policies that are still in a Pending or failed state after a change.
- Automate post-change validation as part of a change management or compliance workflow.
The DistributionStatus field returns one of the following values:
- Success : Policy is fully distributed and live for all targeted users.
- Pending : Policy change is queued or propagation has not yet completed.
- Failed : An error occurred during distribution; immediate investigation recommended.
This script is especially useful in regulated environments where you need to confirm
that a sensitivity label policy is in force before closing a change management ticket
or meeting a compliance deadline.
.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
.PARAMETER UserPrincipalName
The UPN of the admin account used to authenticate to Security & Compliance PowerShell.
Must have Compliance Administrator or Global Administrator rights.
.PARAMETER ShowAllPolicies
Switch parameter. When specified, the script outputs ALL policies regardless of status.
By default, only policies that are NOT in a 'Success' state are highlighted.
.EXAMPLE
# Run the script and show only non-successful (pending/failed) policies:
.\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com
.EXAMPLE
# Run the script and show ALL policies including successfully synced ones:
.\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com -ShowAllPolicies
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, HelpMessage = 'Enter the UPN of the compliance/global admin account.')]
[ValidateNotNullOrEmpty()]
[string]$UserPrincipalName,
[Parameter(Mandatory = $false, HelpMessage = 'Show all policies, including successfully synced ones.')]
[switch]$ShowAllPolicies
)
#region --- Module Check and Installation ---
Write-Host "[INFO] Checking for ExchangeOnlineManagement module..." -ForegroundColor Cyan
try {
if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
Write-Host "[INFO] ExchangeOnlineManagement module not found. Installing for current user..." -ForegroundColor Yellow
Install-Module -Name ExchangeOnlineManagement -Force -Scope CurrentUser -ErrorAction Stop
Write-Host "[INFO] Module installed successfully." -ForegroundColor Green
} else {
Write-Host "[INFO] ExchangeOnlineManagement module is already installed." -ForegroundColor Green
}
} catch {
Write-Error "[ERROR] Failed to install ExchangeOnlineManagement module. Please install it manually. Details: $_"
exit 1
}
#endregion
#region --- Connect to Security & Compliance PowerShell ---
Write-Host "[INFO] Connecting to Security & Compliance PowerShell as '$UserPrincipalName'..." -ForegroundColor Cyan
try {
Connect-IPPSSession -UserPrincipalName $UserPrincipalName -ErrorAction Stop
Write-Host "[INFO] Successfully connected to Security & Compliance PowerShell." -ForegroundColor Green
} catch {
Write-Error "[ERROR] Failed to connect to Security & Compliance PowerShell. Details: $_"
exit 1
}
#endregion
#region --- Retrieve Label Policies ---
Write-Host "[INFO] Retrieving all sensitivity label publishing policies..." -ForegroundColor Cyan
try {
$allPolicies = Get-LabelPolicy -ErrorAction Stop | Select-Object -Property Name, Guid, DistributionStatus, LastModifiedTime, WhenCreated
} catch {
Write-Error "[ERROR] Failed to retrieve label policies. Ensure the account has the required permissions. Details: $_"
exit 1
}
if (-not $allPolicies) {
Write-Warning "[WARN] No sensitivity label policies were found in this tenant."
exit 0
}
Write-Host "[INFO] Total policies retrieved: $($allPolicies.Count)" -ForegroundColor Cyan
#endregion
#region --- Display All Policies (if requested) ---
if ($ShowAllPolicies) {
Write-Host "`n=== ALL Sensitivity Label Policies ===" -ForegroundColor White
$allPolicies | Format-Table -AutoSize
}
#endregion
#region --- Identify Non-Successful Policies ---
Write-Host "`n[INFO] Checking for policies that are NOT in a 'Success' state..." -ForegroundColor Cyan
# Filter for any policy that has not fully synced
$pendingPolicies = $allPolicies | Where-Object { $_.DistributionStatus -ne 'Success' }
if ($pendingPolicies.Count -eq 0) {
Write-Host "[SUCCESS] All sensitivity label policies have a DistributionStatus of 'Success'. No action required." -ForegroundColor Green
} else {
Write-Warning "[WARN] The following $($pendingPolicies.Count) policy/policies have NOT completed distribution:"
$pendingPolicies | Format-Table -AutoSize
# Separate and call out any explicitly failed policies for immediate attention
$failedPolicies = $pendingPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }
if ($failedPolicies.Count -gt 0) {
Write-Host "`n[CRITICAL] The following policies have a 'Failed' distribution status and require immediate investigation:" -ForegroundColor Red
$failedPolicies | Format-Table -AutoSize
}
}
#endregion
#region --- Summary Report ---
Write-Host "`n=== Sensitivity Label Policy Sync Status Summary ===" -ForegroundColor White
Write-Host "Total Policies : $($allPolicies.Count)"
Write-Host "Successful : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Success' }).Count)" -ForegroundColor Green
Write-Host "Pending : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Pending' }).Count)" -ForegroundColor Yellow
Write-Host "Failed : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }).Count)" -ForegroundColor Red
Write-Host "Other/Unknown : $(($allPolicies | Where-Object { $_.DistributionStatus -notin @('Success','Pending','Failed') }).Count)" -ForegroundColor Gray
Write-Host "===================================================`n" -ForegroundColor White
#endregion
Intune Secure Boot and OS Compliance Detection Script
Detects Secure Boot status and OS build version on Windows 11 devices for use as an Intune Proactive Remediation detection script to assess fleet readiness ahead of the 2026 Secure Boot certificate expiry.
<#
.SYNOPSIS
Detects Secure Boot status and OS build version for Intune Proactive Remediation compliance assessment.
.DESCRIPTION
This script is designed to be deployed as an Intune Proactive Remediation (Remediations) detection script
to assess Windows 11 device readiness ahead of the Microsoft Secure Boot certificate rotation in 2026.
It performs the following checks on each managed endpoint:
- Queries Secure Boot status using Confirm-SecureBootUEFI
- Retrieves the current OS build number and Windows version
- Outputs a structured JSON object for consumption by the Intune Remediations engine
Devices where Secure Boot is disabled or unsupported, or where the OS build is below the
acceptable minimum, can be identified from the Intune Remediations results and targeted for
remediation before the certificate expiry deadline in June 2026.
Deploy this script under:
Intune > Devices > Remediations > Create > Detection Script
Results are visible in the Intune portal under the Remediations node and can be exported
to CSV for further filtering and reporting.
.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
.EXAMPLE
# Run locally on a single device to verify output before deploying via Intune:
.\Detect-SecureBootCompliance.ps1
# Expected output (JSON):
# {"ComputerName":"DESKTOP-ABC123","SecureBootEnabled":true,"OSVersion":"22H2","OSBuild":"22621"}
.EXAMPLE
# Deploy as an Intune Proactive Remediation Detection Script:
# 1. Navigate to Intune > Devices > Remediations > + Create
# 2. Paste this script into the Detection Script field
# 3. Set 'Run this script using the logged-on credentials' to No (run as SYSTEM)
# 4. Assign to a device group containing your Windows 11 fleet
# 5. Review results under the Remediations node and export to CSV for analysis
#>
[CmdletBinding()]
param()
# ---------------------------------------------------------------------------
# Step 1: Determine Secure Boot status
# Confirm-SecureBootUEFI returns:
# $true - Secure Boot is enabled and active
# $false - Secure Boot is supported but currently disabled
# throws - Hardware does not support Secure Boot (legacy BIOS or unsupported firmware)
# ---------------------------------------------------------------------------
try {
$SecureBoot = Confirm-SecureBootUEFI
} catch {
# Device does not support Secure Boot (e.g., non-UEFI hardware or CSM-only boot)
$SecureBoot = "Unsupported"
}
# ---------------------------------------------------------------------------
# Step 2: Collect OS version information
# OsBuildNumber surfaces the numeric build (e.g., 22621 for Windows 11 22H2)
# WindowsVersion surfaces the marketing version string (e.g., "22H2")
# Get-ComputerInfo can be slow; acceptable in a detection script context.
# ---------------------------------------------------------------------------
try {
$ComputerInfo = Get-ComputerInfo -ErrorAction Stop
$OSBuild = $ComputerInfo.OsBuildNumber
$OSVersion = $ComputerInfo.WindowsVersion
} catch {
# Fallback to registry-based retrieval if Get-ComputerInfo fails
$OSBuild = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name CurrentBuildNumber -ErrorAction SilentlyContinue).CurrentBuildNumber
$OSVersion = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name DisplayVersion -ErrorAction SilentlyContinue).DisplayVersion
}
# ---------------------------------------------------------------------------
# Step 3: Build structured output object
# The JSON output is consumed by Intune Remediations for reporting.
# Fields:
# ComputerName - Hostname of the device
# SecureBootEnabled - True / False / "Unsupported"
# OSVersion - Windows release version string (e.g., "23H2")
# OSBuild - Numeric OS build number (e.g., 22631)
# ---------------------------------------------------------------------------
$Output = [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
SecureBootEnabled = $SecureBoot
OSVersion = $OSVersion
OSBuild = $OSBuild
}
# ---------------------------------------------------------------------------
# Step 4: Emit compact JSON to stdout for Intune to capture
# -Compress removes whitespace to keep the output on a single line,
# which is friendlier for Intune's output field length constraints.
# ---------------------------------------------------------------------------
Write-Output ($Output | ConvertTo-Json -Compress)
# ---------------------------------------------------------------------------
# Step 5: Exit code convention for Intune Proactive Remediations
# Exit 0 = detected no issue (compliant) — no remediation script will run
# Exit 1 = issue detected (non-compliant) — triggers the paired remediation script
#
# Evaluate compliance criteria:
# - Secure Boot must be enabled (not False or Unsupported)
# - OS build should meet the minimum required threshold
# Update $MinimumBuild to reflect your organisation's current baseline.
# ---------------------------------------------------------------------------
$MinimumBuild = 22621 # Windows 11 22H2 — adjust to your required minimum
$isSecureBootCompliant = ($SecureBoot -eq $true)
$isBuildCompliant = ($OSBuild -ge $MinimumBuild)
if ($isSecureBootCompliant -and $isBuildCompliant) {
# Device meets all compliance criteria — no remediation needed
exit 0
} else {
# Device is non-compliant — Intune will trigger the paired remediation script
exit 1
}