Check Connector Health
This script checks the health of all tenant-level Intune connectors in a single run: Apple push notification certificate and DEP token expiry and sync state, VPP tokens, the Managed Google Play binding and app sync status, NDES and certificate connectors, and Mobile Threat Defense partner connectors with their heartbeat state. Every connector is scored healthy, warning, or critical, so a silent connector failure (expired token, stale sync, unresponsive partner) surfaces before users notice broken enrollments or app installs.
New to runbook deployment? Follow the step-by-step guide from the Deploy to Azure button to the first scheduled run, including granting Graph permissions to the managed identity.
// QUALITY CHECKS
Validation status
Quality checks
All checks pass- ParsePass
- LintPass
- MetadataPass
- Runbook-readyPass
- Module depsPass
Tests run automatically on every change. What does each check mean?
// REQUIRED PERMISSIONS
Microsoft Graph scopes
DeviceManagementServiceConfig.Read.AllAllows the app to read Microsoft Intune service properties including device enrollment and third party service connection configuration, without a signed-in user.
DeviceManagementConfiguration.Read.AllAllows the app to read properties of Microsoft Intune-managed device configuration and device compliance policies and their assignment to groups, without a signed-in user.
DeviceManagementApps.Read.AllAllows the app to read the properties, group assignments and status of apps, app configurations and app protection policies managed by Microsoft Intune, without a signed-in user.
Running this as an Azure Automation runbook? These scopes must be granted to the account's managed identity, which has no portal UI. The deployment walkthrough shows the exact Cloud Shell commands.
// CHANGELOG
Version history
Entry · 01
1.2 - Added Azure Automation contract validation, portal-safe boolean parameters, beta Graph endpoints, and terminating paging errors
Entry · 02
1.1 - Azure Automation now records script progress, outcomes, and summaries in job history
Entry · 03
1.0 - Initial release
// CODE
Source
<#
.TITLE
Check Connector Health
.SYNOPSIS
One health report for every Intune tenant connector: Apple DEP/APNs/VPP, Managed Google Play, NDES, certificate connectors, and Mobile Threat Defense.
.DESCRIPTION
This script checks the health of all tenant-level Intune connectors in a single
run: Apple push notification certificate and DEP token expiry and sync state,
VPP tokens, the Managed Google Play binding and app sync status, NDES and
certificate connectors, and Mobile Threat Defense partner connectors with their
heartbeat state. Every connector is scored healthy, warning, or critical, so a
silent connector failure (expired token, stale sync, unresponsive partner)
surfaces before users notice broken enrollments or app installs.
.TAGS
Monitoring
.MINROLE
Intune Administrator
.PERMISSIONS
DeviceManagementServiceConfig.Read.All,DeviceManagementConfiguration.Read.All,DeviceManagementApps.Read.All
.AUTHOR
Ugur Koc
.VERSION
1.2
.CHANGELOG
1.2 - Added Azure Automation contract validation, portal-safe boolean parameters, beta Graph endpoints, and terminating paging errors
1.1 - Azure Automation now records script progress, outcomes, and summaries in job history
1.0 - Initial release
.LASTUPDATE
2026-07-30
.EXAMPLE
.\check-connector-health.ps1
Checks all connectors with a 30-day expiry warning window
.EXAMPLE
.\check-connector-health.ps1 -ExpiryWarningDays 60 -ExportToCsv "true"
Uses a 60-day warning window and exports the report to CSV
.NOTES
- Requires Microsoft.Graph.Authentication module
- Connectors that are not configured in the tenant are reported as NotConfigured, not as failures
- Sync staleness thresholds: DEP sync older than 7 days and Google Play app sync older than 7 days raise warnings
- Uses beta Graph endpoints because most connector surfaces are not exposed on v1.0
- Local interactive sign-in uses the MgGraphCommunity module to avoid the Graph SDK's mandatory WAM broker on Windows
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false, HelpMessage = "Days before certificate/token expiry to raise a warning")]
[ValidateRange(1, 365)]
[int]$ExpiryWarningDays = 30,
[Parameter(Mandatory = $false, HelpMessage = "Export results to CSV")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$ExportToCsv,
[Parameter(Mandatory = $false, HelpMessage = "Output path for exports")]
[string]$OutputPath = ".",
[Parameter(Mandatory = $false, HelpMessage = "Force module installation without prompting")]
[ValidateSet("true", "false", "1", "0", '$true', '$false')]
[string]$ForceModuleInstall
)
# Normalize the local module-install override for Azure Automation parameter binding.
$forceModuleInstallRaw = [string]$ForceModuleInstall
Remove-Variable -Name ForceModuleInstall
if ([string]::IsNullOrWhiteSpace($forceModuleInstallRaw)) {
$ForceModuleInstall = $false
}
elseif ($forceModuleInstallRaw.Trim().ToLowerInvariant() -in @("true", "1", '$true')) {
$ForceModuleInstall = $true
}
elseif ($forceModuleInstallRaw.Trim().ToLowerInvariant() -in @("false", "0", '$false')) {
$ForceModuleInstall = $false
}
else {
throw "Parameter 'ForceModuleInstall' accepts only true, false, 1, 0, $true, or $false."
}
# Azure Automation supplies portal parameter values as strings. Normalize the
# public boolean parameters once so local and runbook execution use real booleans.
foreach ($runbookBooleanParameter in @('ExportToCsv')) {
$runbookBooleanRaw = [string](Get-Variable -Name $runbookBooleanParameter -ValueOnly)
Remove-Variable -Name $runbookBooleanParameter
if ([string]::IsNullOrWhiteSpace($runbookBooleanRaw)) {
Set-Variable -Name $runbookBooleanParameter -Value $false
continue
}
switch ($runbookBooleanRaw.Trim().ToLowerInvariant()) {
{ $_ -in @("true", "1", '$true') } {
Set-Variable -Name $runbookBooleanParameter -Value $true
}
{ $_ -in @("false", "0", '$false') } {
Set-Variable -Name $runbookBooleanParameter -Value $false
}
default {
throw "Parameter '$runbookBooleanParameter' accepts only true, false, 1, 0, $true, or $false."
}
}
}
# ============================================================================
# ENVIRONMENT DETECTION AND SETUP
# ============================================================================
function Initialize-RequiredModule {
param(
[string[]]$ModuleNames,
[bool]$IsAutomationEnvironment,
[bool]$ForceInstall = $false
)
foreach ($ModuleName in $ModuleNames) {
Write-Verbose "Checking module: $ModuleName"
$module = Get-Module -ListAvailable -Name $ModuleName | Select-Object -First 1
if (-not $module) {
if ($IsAutomationEnvironment) {
throw "Module '$ModuleName' is not available in Azure Automation"
}
else {
Write-Information "Module '$ModuleName' not found. Installing..." -InformationAction Continue
if (-not $ForceInstall) {
$response = Read-Host "Install module '$ModuleName'? (Y/N)"
if ($response -notmatch '^[Yy]') {
throw "Module '$ModuleName' is required but installation was declined."
}
}
try {
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$scope = if ($isAdmin) { "AllUsers" } else { "CurrentUser" }
Install-Module -Name $ModuleName -Scope $scope -Force -AllowClobber -Repository PSGallery
Write-Information "✓ Successfully installed '$ModuleName'" -InformationAction Continue
}
catch {
throw "Failed to install module '$ModuleName': $($_.Exception.Message)"
}
}
}
Import-Module -Name $ModuleName -Force -ErrorAction Stop
}
}
# Detect execution environment
$IsAzureAutomation = $null -ne $PSPrivateMetadata.JobId.Guid
# Initialize required modules
$RequiredModules = @("Microsoft.Graph.Authentication")
# MgGraphCommunity gives WAM-free interactive sign-in for local runs
if (-not $IsAzureAutomation) {
$RequiredModules += "MgGraphCommunity"
}
try {
Initialize-RequiredModule -ModuleNames $RequiredModules -IsAutomationEnvironment $IsAzureAutomation -ForceInstall $ForceModuleInstall
Write-Verbose "✓ All required modules are available"
}
catch {
Write-Error "Module initialization failed: $_"
exit 1
}
# ============================================================================
# AUTHENTICATION
# ============================================================================
try {
if ($IsAzureAutomation) {
Write-Output "Connecting to Microsoft Graph using Managed Identity..."
Connect-MgGraph -Identity -NoWelcome -ErrorAction Stop
}
else {
Write-Output "Connecting to Microsoft Graph..."
$Scopes = @(
"DeviceManagementServiceConfig.Read.All",
"DeviceManagementConfiguration.Read.All",
"DeviceManagementApps.Read.All"
)
Connect-MgGraphCommunity -Scopes $Scopes -NoWelcome -ErrorAction Stop
}
Write-Output "✓ Successfully connected to Microsoft Graph"
}
catch {
Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
exit 1
}
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
function Get-MgGraphAllPage {
param(
[string]$Uri,
[int]$DelayMs = 100
)
$allResults = @()
$nextLink = $Uri
do {
try {
if ($allResults.Count -gt 0) {
Start-Sleep -Milliseconds $DelayMs
}
$response = Invoke-MgGraphRequest -Uri $nextLink -Method GET
if ($null -ne $response.value) {
$allResults += $response.value
}
else {
$allResults += $response
}
$nextLink = $response.'@odata.nextLink'
}
catch {
if ($_.Exception.Message -like "*429*") {
Write-Information "Rate limit hit, waiting 60 seconds..." -InformationAction Continue
Start-Sleep -Seconds 60
continue
}
throw "Error fetching data: $($_.Exception.Message)"
}
} while ($nextLink)
return $allResults
}
$script:ConnectorReport = [System.Collections.Generic.List[Object]]::new()
function Add-ConnectorResult {
param(
[string]$Connector,
[string]$Instance,
[string]$Status,
[string]$Detail
)
$script:ConnectorReport.Add([PSCustomObject]@{
Connector = $Connector
Instance = $Instance
Status = $Status
Detail = $Detail
})
}
function Get-ExpiryStatus {
param(
[object]$ExpiryValue,
[int]$WarningDays
)
if (-not $ExpiryValue) {
return @{ Status = "Warning"; Detail = "No expiration date available" }
}
$expiry = [DateTime]::Parse($ExpiryValue.ToString())
$daysLeft = [math]::Round(($expiry - (Get-Date)).TotalDays, 0)
if ($daysLeft -lt 0) {
return @{ Status = "Critical"; Detail = "EXPIRED $([math]::Abs($daysLeft)) days ago ($($expiry.ToString('yyyy-MM-dd')))" }
}
if ($daysLeft -le $WarningDays) {
return @{ Status = "Warning"; Detail = "Expires in $daysLeft days ($($expiry.ToString('yyyy-MM-dd')))" }
}
return @{ Status = "Healthy"; Detail = "Expires in $daysLeft days ($($expiry.ToString('yyyy-MM-dd')))" }
}
# ============================================================================
# MAIN SCRIPT LOGIC
# ============================================================================
try {
$staleSyncThreshold = (Get-Date).AddDays(-7)
# ----- Apple push notification certificate -----
Write-Output "Checking Apple MDM push certificate..."
try {
$apns = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceManagement/applePushNotificationCertificate" -Method GET
if ($apns -and $apns.appleIdentifier) {
$expiryInfo = Get-ExpiryStatus -ExpiryValue $apns.expirationDateTime -WarningDays $ExpiryWarningDays
Add-ConnectorResult -Connector "Apple MDM Push Certificate" -Instance $apns.appleIdentifier -Status $expiryInfo.Status -Detail $expiryInfo.Detail
}
else {
Add-ConnectorResult -Connector "Apple MDM Push Certificate" -Instance "-" -Status "NotConfigured" -Detail "No APNs certificate uploaded"
}
}
catch {
Add-ConnectorResult -Connector "Apple MDM Push Certificate" -Instance "-" -Status "NotConfigured" -Detail "Not configured or not readable"
}
# ----- Apple DEP tokens -----
Write-Output "Checking Apple DEP tokens..."
try {
$depTokens = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceManagement/depOnboardingSettings"
if (@($depTokens).Count -eq 0) {
Add-ConnectorResult -Connector "Apple DEP Token" -Instance "-" -Status "NotConfigured" -Detail "No Automated Device Enrollment tokens"
}
foreach ($token in $depTokens) {
$expiryInfo = Get-ExpiryStatus -ExpiryValue $token.tokenExpirationDateTime -WarningDays $ExpiryWarningDays
$status = $expiryInfo.Status
$detail = $expiryInfo.Detail
# A valid token with a failing or stale sync is still broken
$lastSync = if ($token.lastSuccessfulSyncDateTime) { [DateTime]::Parse($token.lastSuccessfulSyncDateTime.ToString()) } else { $null }
if ($token.lastSyncErrorCode -and $token.lastSyncErrorCode -ne 0) {
if ($status -eq "Healthy") { $status = "Warning" }
$detail += " | last sync error code: $($token.lastSyncErrorCode)"
}
if ($lastSync -and $lastSync -lt $staleSyncThreshold) {
if ($status -eq "Healthy") { $status = "Warning" }
$detail += " | last successful sync: $($lastSync.ToString('yyyy-MM-dd'))"
}
Add-ConnectorResult -Connector "Apple DEP Token" -Instance $token.tokenName -Status $status -Detail $detail
}
}
catch {
Add-ConnectorResult -Connector "Apple DEP Token" -Instance "-" -Status "Error" -Detail $_.Exception.Message
}
# ----- Apple VPP tokens -----
Write-Output "Checking Apple VPP tokens..."
try {
$vppTokens = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceAppManagement/vppTokens"
if (@($vppTokens).Count -eq 0) {
Add-ConnectorResult -Connector "Apple VPP Token" -Instance "-" -Status "NotConfigured" -Detail "No VPP tokens"
}
foreach ($token in $vppTokens) {
$expiryInfo = Get-ExpiryStatus -ExpiryValue $token.expirationDateTime -WarningDays $ExpiryWarningDays
$status = if ($token.state -ne "valid") { "Critical" } else { $expiryInfo.Status }
$detail = "State: $($token.state) | $($expiryInfo.Detail)"
Add-ConnectorResult -Connector "Apple VPP Token" -Instance $token.appleId -Status $status -Detail $detail
}
}
catch {
Add-ConnectorResult -Connector "Apple VPP Token" -Instance "-" -Status "Error" -Detail $_.Exception.Message
}
# ----- Managed Google Play -----
Write-Output "Checking Managed Google Play binding..."
try {
$googlePlay = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceManagement/androidManagedStoreAccountEnterpriseSettings" -Method GET
if ($googlePlay.bindStatus -eq "notBound") {
Add-ConnectorResult -Connector "Managed Google Play" -Instance "-" -Status "NotConfigured" -Detail "Tenant is not bound to Managed Google Play"
}
else {
$status = "Healthy"
$detail = "Bind status: $($googlePlay.bindStatus) | app sync: $($googlePlay.lastAppSyncStatus)"
if ($googlePlay.lastAppSyncStatus -notin @("success", "none")) {
$status = "Warning"
}
$lastAppSync = if ($googlePlay.lastAppSyncDateTime) { [DateTime]::Parse($googlePlay.lastAppSyncDateTime.ToString()) } else { $null }
if ($lastAppSync) {
$detail += " | last sync: $($lastAppSync.ToString('yyyy-MM-dd'))"
if ($lastAppSync -lt $staleSyncThreshold) { $status = "Warning" }
}
Add-ConnectorResult -Connector "Managed Google Play" -Instance $googlePlay.ownerOrganizationName -Status $status -Detail $detail
}
}
catch {
Add-ConnectorResult -Connector "Managed Google Play" -Instance "-" -Status "Error" -Detail $_.Exception.Message
}
# ----- NDES connectors -----
Write-Output "Checking NDES connectors..."
try {
$ndesConnectors = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceManagement/ndesConnectors"
if (@($ndesConnectors).Count -eq 0) {
Add-ConnectorResult -Connector "NDES Connector" -Instance "-" -Status "NotConfigured" -Detail "No NDES connectors installed"
}
foreach ($connector in $ndesConnectors) {
$status = if ($connector.state -eq "active") { "Healthy" } else { "Critical" }
$lastConnection = if ($connector.lastConnectionDateTime) { [DateTime]::Parse($connector.lastConnectionDateTime.ToString()) } else { $null }
$detail = "State: $($connector.state)"
if ($lastConnection) {
$detail += " | last connection: $($lastConnection.ToString('yyyy-MM-dd HH:mm'))"
if ($lastConnection -lt $staleSyncThreshold -and $status -eq "Healthy") { $status = "Warning" }
}
Add-ConnectorResult -Connector "NDES Connector" -Instance $connector.displayName -Status $status -Detail $detail
}
}
catch {
Add-ConnectorResult -Connector "NDES Connector" -Instance "-" -Status "Error" -Detail $_.Exception.Message
}
# ----- Certificate connectors -----
Write-Output "Checking certificate connectors..."
try {
# This surface returns errors in tenants that never installed a connector
$certificateConnectors = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceManagement/certificateConnectorDetails"
if (@($certificateConnectors).Count -eq 0) {
Add-ConnectorResult -Connector "Certificate Connector" -Instance "-" -Status "NotConfigured" -Detail "No certificate connectors installed"
}
foreach ($connector in $certificateConnectors) {
$lastCheckIn = if ($connector.lastCheckinDateTime) { [DateTime]::Parse($connector.lastCheckinDateTime.ToString()) } else { $null }
$status = "Healthy"
$detail = "Version: $($connector.connectorVersion)"
if ($lastCheckIn) {
$detail += " | last check-in: $($lastCheckIn.ToString('yyyy-MM-dd HH:mm'))"
if ($lastCheckIn -lt $staleSyncThreshold) { $status = "Critical" }
}
Add-ConnectorResult -Connector "Certificate Connector" -Instance $connector.machineName -Status $status -Detail $detail
}
}
catch {
Add-ConnectorResult -Connector "Certificate Connector" -Instance "-" -Status "NotConfigured" -Detail "No certificate connector infrastructure in this tenant"
}
# ----- Mobile Threat Defense connectors -----
Write-Output "Checking Mobile Threat Defense connectors..."
try {
$mtdConnectors = Get-MgGraphAllPage -Uri "https://graph.microsoft.com/beta/deviceManagement/mobileThreatDefenseConnectors"
if (@($mtdConnectors).Count -eq 0) {
Add-ConnectorResult -Connector "Mobile Threat Defense" -Instance "-" -Status "NotConfigured" -Detail "No MTD connectors"
}
foreach ($connector in $mtdConnectors) {
$status = switch ($connector.partnerState) {
"available" { "Healthy" }
"enabled" { "Healthy" }
"unresponsive" { "Critical" }
default { "Warning" }
}
$lastHeartbeat = if ($connector.lastHeartbeatDateTime) { [DateTime]::Parse($connector.lastHeartbeatDateTime.ToString()) } else { $null }
$detail = "Partner state: $($connector.partnerState)"
if ($lastHeartbeat) {
$detail += " | last heartbeat: $($lastHeartbeat.ToString('yyyy-MM-dd HH:mm'))"
}
Add-ConnectorResult -Connector "Mobile Threat Defense" -Instance $connector.id -Status $status -Detail $detail
}
}
catch {
Add-ConnectorResult -Connector "Mobile Threat Defense" -Instance "-" -Status "Error" -Detail $_.Exception.Message
}
# ----- Display results -----
Write-Output "`nCONNECTOR HEALTH REPORT"
Write-Output ("=" * 50)
Write-Output "Warning window: $ExpiryWarningDays days | Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output ("=" * 50)
$statusOrder = @("Critical", "Warning", "Error", "Healthy", "NotConfigured")
foreach ($statusName in $statusOrder) {
$rows = @($script:ConnectorReport | Where-Object { $_.Status -eq $statusName })
if ($rows.Count -eq 0) { continue }
Write-Output "`n[$statusName]"
foreach ($row in $rows) {
Write-Output " $($row.Connector) | $($row.Instance)"
Write-Output " $($row.Detail)"
}
}
# Summary
$criticalCount = @($script:ConnectorReport | Where-Object { $_.Status -eq "Critical" }).Count
$warningCount = @($script:ConnectorReport | Where-Object { $_.Status -eq "Warning" }).Count
Write-Output "`n"
Write-Output ("=" * 50)
Write-Output "Summary: $($script:ConnectorReport.Count) connector checks | $criticalCount critical | $warningCount warnings"
Write-Output ("=" * 50)
# Export to CSV if requested
if ($ExportToCsv) {
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$csvPath = Join-Path $OutputPath "Connector_Health_$timestamp.csv"
$script:ConnectorReport | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Output "✓ CSV report saved: $csvPath"
}
}
catch {
Write-Error "Script execution failed: $($_.Exception.Message)"
exit 1
}
finally {
try {
$null = Disconnect-MgGraph
Write-Output "✓ Disconnected from Microsoft Graph"
}
catch {
Write-Verbose "Graph disconnection completed"
}
}
// NOTES
Author notes
- Requires Microsoft.Graph.Authentication module - Connectors that are not configured in the tenant are reported as NotConfigured, not as failures - Sync staleness thresholds: DEP sync older than 7 days and Google Play app sync older than 7 days raise warnings - Uses beta Graph endpoints because most connector surfaces are not exposed on v1.0 - Local interactive sign-in uses the MgGraphCommunity module to avoid the Graph SDK's mandatory WAM broker on Windows
// RELATED
Scripts that travel together.
Picked by shared tags, category, and script type — nothing magic, just metadata overlap.
Get Policy Drift Report
This script takes a baseline folder created by backup-intune-configuration.ps1 and compares the tenant's current state against it: settings catalog policies (full setting bodies), classic device configuration profiles, and compliance policies. Policies are matched by object ID, and their configuration is compared as normalized JSON with volatile properties (timestamps, versions) removed. The report shows policies that were added, deleted, or modified since the baseline, making unreviewed configuration drift visible for change control.
MonitoringGet Outdated iOS Devices Report
Connects to Microsoft Graph and retrieves Intune-managed iOS devices, including their assigned user and last check-in date. Devices with an iOS major version lower than the older of the two supported major releases are exported to a timestamped CSV file. The supported major versions can be updated by parameter when Apple releases a new major version.
MonitoringApple Token Validity Checker
This script connects to Microsoft Graph and retrieves all Apple Device Enrollment Program (DEP) tokens and Apple Push Notification Certificates configured in Intune. It checks their validity status, expiration dates, and sync status to help administrators proactively manage Apple Business Manager integrations. The script generates detailed reports in CSV format, highlighting tokens and certificates that are expired, expiring soon, or have sync issues.
Monitoring