Detecting Device Certificate Expiration Before It Breaks Management with PowerShell
A read-only PowerShell detector that reports days remaining on the MDM device certificate, so expired or expiring certs are caught before check-in breaks.
C
CloudEngineerHub Team
Published: September 6, 2026· Last Updated: September 28, 2026·8 min read
Certificate problems are the quietest way an Intune fleet falls apart. Every managed Windows device holds an MDM enrollment certificate, issued during enrollment and used to authenticate every check-in. While the device checks in normally, that certificate gets renewed long before expiry and nobody ever thinks about it. But a device that loses connectivity for a few weeks, sits in a cupboard during a project pause, or drifts into a state where check-in fails, can sail past renewal and wake up one day with an expired credential. From the admin center it just looks like a device that stopped checking in. This article provides a read-only PowerShell detection script that looks directly at the machine certificate store, finds the MDM enrollment certificates by their issuer, MS-Organization-Access, and reports exactly how many days remain before the current one expires. A configurable warning window, thirty days by default, turns the slow approach of expiry into a visible, actionable signal in Intune's remediation reporting instead of a surprise outage.
Visual Walkthrough
C
CloudEngineerHub Team
Author
The CloudEngineerHub editorial team — Microsoft endpoint management and cloud engineers writing hands-on guides on Intune, Azure, Entra ID, Autopilot, Defender and PowerShell. Every article is reviewed against current Microsoft documentation.
Exit 1 flips the device into the remediation queue for this package.
remediate
3
Remediation executes
Fix script runs silently as SYSTEM with a 5-minute budget.
verify
4
Re-run detection
The same detection script must now exit 0 — proof, not hope.
telemetry
5
Results report
Per-device outcome lands in Reports → Remediations for trend analysis.
6
Repeat on schedule
The loop continues — drift gets caught the day it appears.
Continuous cycle
Proactive Remediations — The Detect → Fix → Verify Loop. 1. Detection script runs: Scheduled (daily/hourly): exit 0 healthy, exit 1 unhealthy — nothing more. — 2. Verdict: unhealthy: Exit 1 flips the device into the remediation queue for this package. — 3. Remediation executes: Fix script runs silently as SYSTEM with a 5-minute budget. — 4. Re-run detection: The same detection script must now exit 0 — proof, not hope. — 5. Results report: Per-device outcome lands in Reports → Remediations for trend analysis. — 6. Repeat on schedule: The loop continues — drift gets caught the day it appears.
Symptoms
Certificate expiration announces itself as a management outage with mundane symptoms:
Devices stop checking in to Intune; last check-in timestamps grow stale across a subset of the fleet.
The Intune admin center shows those devices as not compliant or unreachable, with no policy or app errors to explain it.
Manual sync from the device fails silently, and the Company Portal shows stale or missing status.
On the device, dsregcmd /status or enrollment diagnostics show authentication problems against the management endpoints.
The pattern concentrates on devices that were offline or unmanaged for long stretches, not on active users.
Possible Causes
The device stopped checking in before renewal
Renewal happens as part of the normal MDM check-in cycle. A device that cannot reach the management endpoints, or that stopped checking in for any reason, misses the renewal window and eventually runs out of certificate lifetime.
Expired certificates left over after re-enrollment
Re-enrollment can leave older certificates in the store alongside the current one. Confusing an expired leftover with the active credential leads troubleshooting in circles; the script explicitly evaluates the certificate with the latest expiry date.
Clock skew on the device
A device whose clock is far off can fail certificate validation, which looks identical to expiration from the client side even when the certificate itself is valid.
Enrollments without a usable certificate
A device can carry an MDM enrollment record in the registry while its certificate is missing, for example after an interrupted cleanup or a failed re-enrollment. That state cannot authenticate and needs re-enrollment.
Intentional or accidental store cleanup
Hardening scripts or manual hygiene operations that purge "unknown" certificates from LocalMachine\My occasionally remove MDM credentials, which breaks check-in on the next cycle.
Detection Script
The script is read-only and completes in seconds. It runs in 64-bit SYSTEM context, enumerates Cert:\LocalMachine\My, and reports every certificate issued by MS-Organization-Access with its expiry and days remaining, plus any certificate with Intune in the subject or issuer as context. The certificate with the latest NotAfter is evaluated against a warning window you can tune with a parameter.
PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#Requires -RunAsAdministrator
[CmdletBinding()]
param(
# Flag when the current MDM device certificate expires within this many days.
[ValidateRange(1, 365)]
[int] $WarningDays = 30
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
<#
.SYNOPSIS
Detection script: reports the remaining lifetime of the MDM device
certificate in the local machine certificate store.
.DESCRIPTION
Read-only. MDM enrollment certificates issued by 'MS-Organization-Access'
are the credentials a device uses to authenticate during Intune check-in.
The script lists those certificates, evaluates the one with the latest
NotAfter date (the one that matters going forward), and flags expiration
inside the warning window. Any certificate with 'Intune'in its subject or
issuer is reported as additional context.
Exit 0 = MDM certificate valid beyond the warning window.
Exit 1 = MDM certificate expired, expiring within the window, or missing
while the device is MDM enrolled.
Exit 2 = device has no MDM enrollment (topic not applicable).
Exit 3 = unexpected error.
#>$logDir = 'C:\ProgramData\Company\Logs'$logFile = Join-Path $logDir'DeviceCertExpiryDetection.log'$mdmCertIssuerPattern = '*MS-Organization-Access*'function Write-DetectionLog {
param([Parameter(Mandatory)][string] $Level, [Parameter(Mandatory)][string] $Message)
if (-not (Test-Path $logDir)) { New-Item -Path$logDir -ItemType Directory -Force | Out-Null }
"$([DateTime]::UtcNow.ToString('o')) [$Level] $Message" | Out-File -FilePath$logFile -Append -Encoding utf8
}
function Test-MdmEnrolled {
# A device-managed MDM enrollment appears as a GUID subkey of # HKLM:\SOFTWARE\Microsoft\Enrollments with EnrollmentType 6.$enrollPath = 'HKLM:\SOFTWARE\Microsoft\Enrollments'if (-not (Test-Path $enrollPath)) { return$false }
foreach ($keyin (Get-ChildItem -Path$enrollPath -ErrorAction SilentlyContinue)) {
$prop = Get-ItemProperty -Path$key.PSPath -Name'EnrollmentType' -ErrorAction SilentlyContinue
if ($null -ne$prop -and$prop.EnrollmentType -eq6) { return$true }
}
return$false
}
try {
Write-DetectionLog 'INFO'"Device certificate expiration detection started. WarningDays=$WarningDays"$allCerts = @(Get-ChildItem -Path'Cert:\LocalMachine\My' -ErrorAction SilentlyContinue)
Write-DetectionLog 'INFO'"Certificates in LocalMachine\My: $($allCerts.Count)" # ---- MDM enrollment certificates ----$mdmCerts = @($allCerts | Where-Object { $_.Issuer -like$mdmCertIssuerPattern })
foreach ($certin ($mdmCerts | Sort-Object -Property NotAfter)) {
$daysLeft = [int][Math]::Floor(($cert.NotAfter - (Get-Date)).TotalDays)
Write-DetectionLog 'INFO' ("MDM enrollment certificate: Subject='{0}' NotAfter={1:u} DaysRemaining={2}" -f$cert.Subject, $cert.NotAfter, $daysLeft)
}
# ---- Intune-named certificates (context only) ----$intuneNamedCerts = @($allCerts | Where-Object { $_.Subject -like'*Intune*' -or$_.Issuer -like'*Intune*' })
foreach ($certin$intuneNamedCerts) {
Write-DetectionLog 'INFO' ("Intune-named certificate (context only): Subject='{0}' Issuer='{1}' NotAfter={2:u}" -f$cert.Subject, $cert.Issuer, $cert.NotAfter)
}
if ($mdmCerts.Count -eq0) {
if (Test-MdmEnrolled) {
Write-DetectionLog 'ERROR''Device is MDM enrolled but no MS-Organization-Access certificate exists in LocalMachine\My. The device cannot authenticate for check-in; re-enrollment is required (admin side).'
exit 1
}
Write-DetectionLog 'WARN''No MDM enrollment found and no MDM device certificate present - topic not applicable to this device.'
exit 2
}
# ---- Evaluate the current certificate ---- # After re-enrollments older certificates can linger; the certificate with # the latest NotAfter is the one that matters going forward.$currentCert = @($mdmCerts | Sort-Object -Property NotAfter -Descending)[0]
$daysRemaining = [int][Math]::Floor(($currentCert.NotAfter - (Get-Date)).TotalDays)
Write-DetectionLog 'INFO' ("Current MDM certificate: NotAfter={0:u} DaysRemaining={1} WarningDays={2}" -f$currentCert.NotAfter, $daysRemaining, $WarningDays)
if ($daysRemaining -lt0) {
Write-DetectionLog 'ERROR'"MDM device certificate EXPIRED $(-$daysRemaining) day(s) ago. Check-in will fail; re-enrollment is the recovery path."
exit 1
}
if ($daysRemaining -lt$WarningDays) {
Write-DetectionLog 'ERROR'"MDM device certificate expires in $daysRemaining day(s), inside the $WarningDays-day warning window. Verify the device can still check in to Intune."
exit 1
}
Write-DetectionLog 'INFO''MDM device certificate is valid beyond the warning window.'
exit 0
}
catch {
Write-DetectionLog 'ERROR'"Unexpected failure: $($_.Exception.Message)"
exit 3
}
finally {
Write-DetectionLog 'INFO''Device certificate expiration detection finished.'
}
Detection Logic
MDM certificate discovery. The script filters Cert:\LocalMachine\My for certificates whose issuer contains MS-Organization-Access, which is the issuer name used for the MDM enrollment certificate a device receives when it enrolls for management. This is a machine-store scan, so it sees device credentials regardless of who is signed in.
Days-remaining accounting. For every MDM certificate it logs the subject, NotAfter, and whole days remaining, computed as the floor of the time delta. Logging all of them matters: fleets that have re-enrolled devices often carry expired leftovers, and seeing both in one log line ends that confusion immediately.
Current certificate selection. The certificate with the latest NotAfter is treated as the current credential, because after any re-enrollment the newest certificate is the one the device will rely on going forward. Older ones are context, not the signal.
Threshold evaluation. If the current certificate is already expired the script exits 1 with the number of days past expiry. If it expires inside the $WarningDays window (30 by default, adjustable when running manually), it exits 1 with the countdown. Otherwise it exits 0.
Enrollment cross-check. If no MDM certificate exists at all, the script checks HKLM:\SOFTWARE\Microsoft\Enrollments for an MDM enrollment (a GUID subkey with EnrollmentType 6). An enrollment without a certificate exits 1 because the device cannot authenticate; no enrollment and no certificate exits 2 as not applicable.
Remediation Script
Detection-only, and the prose matters more than usual here. There is no local renewal path for an MDM device certificate: renewal is part of the check-in flow, and recovery from an expired certificate is re-enrollment, which is an admin-side action (a sync from the admin center where the device is still reachable, or a full re-enrollment where it is not). A local script cannot mint a new credential, and pretending otherwise would leave devices in the same broken state. What this detector changes is lead time: a 30-day warning gives you a month to fix check-in on a device before its credential lapses.
Deploying Through Intune
In the Microsoft Intune admin center, go to Devices → Scripts and remediations and select + Add on the Windows 10/11 platform tab.
Name the package Detect - MDM certificate expiration and note in the description that it is read-only with a 30-day default warning window.
On the Detection script tab, upload detect.ps1. Set Run script in 64-bit PowerShell: Yes and Run this script using signed-on credentials: No so it runs as SYSTEM.
Leave Enforce script signature check: No unless your organization signs internal scripts and deploys the signing certificates.
On the Remediation script tab, select No remediation script; the fix path is re-enrollment, not a local change.
Set Frequency to Weekly. Certificate lifetimes are long; weekly detection gives you plenty of runway inside a 30-day window.
On Assignments, target all Windows devices enrolled in Intune. Paradoxically, the devices that need this most are the ones about to stop reporting, so wide assignment is correct here.
Review and create.
Post-specific notes:
Devices that already stopped checking in will not run the package; use your stale-device process to catch those, and treat this detector as the early-warning layer for devices that still check in.
The warning window only applies when you run the script manually with -WarningDays; through Intune the 30-day default applies.
Pair the results with the devices-not-checking-in view: an exit 1 plus a stale last-check-in date is a device already in trouble.
Visual Walkthrough
NDES + Intune certificate connectors demystified end to end.
Interactive FlowSCEP Certificates — Request to Renewal6/6
1
SCEP policy assigned
Intune profile: CA URL, template, SAN, validity window.
challenge
2
Challenge generated
Intune issues one-time challenge password to device.
request
3
CSR sent to NDES
Device requests cert via the connector with challenge.
issue
4
CA validates & issues
Enterprise CA issues per template rules.
install
5
Cert installed & chained
Root + issuing chain validated; Wi-Fi/VPN consume it.
6
Renewal window monitored
Detection alerts before expiry breaks Wi-Fi/VPN/S/MIME.
SCEP Certificates — Request to Renewal. 1. SCEP policy assigned: Intune profile: CA URL, template, SAN, validity window. — 2. Challenge generated: Intune issues one-time challenge password to device. — 3. CSR sent to NDES: Device requests cert via the connector with challenge. — 4. CA validates & issues: Enterprise CA issues per template rules. — 5. Cert installed & chained: Root + issuing chain validated; Wi-Fi/VPN consume it. — 6. Renewal window monitored: Detection alerts before expiry breaks Wi-Fi/VPN/S/MIME.
Exit Codes
Intune treats any non-zero detection exit as remediation needed. For this package that flag means "work this device through the re-enrollment path".
Code
Meaning
0
MDM device certificate valid beyond the warning window
1
Certificate expired, expiring within the window, or missing while the device is MDM enrolled
2
No MDM enrollment present (topic not applicable)
3
Unexpected script error - inspect the log
Logging
The script writes to C:\ProgramData\Company\Logs\DeviceCertExpiryDetection.log. Each line carries a UTC timestamp, a level, and a message; MDM certificates are logged individually with subject, NotAfter, and days remaining, so one run gives you a complete picture of the device's enrollment credentials. Expect three to six lines per run; the file grows slowly and monthly rotation is fine. When a device exits 1, cross-reference its last check-in date in the admin center and the enrollment diagnostics on the device to decide between a forced sync and full re-enrollment.
Troubleshooting the Script
Exit 2 on a device you know is enrolled. The registry cross-check looks for EnrollmentType 6 under GUID subkeys of the Enrollments key; run dsregcmd /status and inspect the enrollment sections manually if the result contradicts the admin center.
No MDM certificate on a healthy device. Some enrollment paths leave credentials in a different store or use newer issuers on preview builds; verify in the certificates MMC before assuming breakage, and adjust your process if your build behaves differently.
Exit 3 after store access errors. Application control or endpoint security tools occasionally block cert-store enumeration for scripts; get an exclusion approved rather than working around it.
Results differ from a manual MMC check. Confirm the script ran in 64-bit SYSTEM context; a redirected file system or different user context can change what the certificate provider returns.
Fleet-wide exits after a certificate authority change. If your tenant migrated enrollment infrastructure, expect a wave of findings; validate a few devices manually before bulk re-enrolling.
How to Validate the Fix
On an enrolled, healthy device, run the script manually in an elevated 64-bit console. Expect exit 0 and log lines naming the MS-Organization-Access certificate with a large days-remaining value.
Find or fabricate a device near expiry (a lab device whose enrollment is old works well). Expect exit 1 with the countdown in the log.
For a device that already stopped checking in, confirm the expired-certificate finding on-device, then re-enroll it through your standard process.
After re-enrollment, re-run detection. Expect a new MS-Organization-Access certificate with a fresh NotAfter and exit 0.
Confirm in the admin center that the device checks in and its status returns to normal.
Production Considerations
Context. Runs as SYSTEM in 64-bit PowerShell; local admin rights are enforced by the #Requires directive. The machine certificate store requires elevation, which is exactly why the directive is present.
Idempotency. The script reads the certificate store and registry and writes nothing except its log. Repeat runs are free.
Side effects. None. No reboots, no store modifications, no network calls.
Security review. No credentials or secrets are handled; the log contains certificate subjects and dates but no private key material. Validate the package in a test ring with your PowerShell automation SME and security team before broad production rollout, and confirm your security tooling is comfortable with cert-store reads from script.
Assignment breadth. Assign widely: this is one of the few detectors where the devices you most need to reach are the ones drifting toward silence.
Can the script renew the certificate instead of just detecting expiry?
No. The MDM device certificate is renewed by the management flow itself while the device checks in, and recovery after expiry is re-enrollment, which is an admin-side action. A local script has no way to mint the credential, and attempting workarounds would leave the device in the same state.
Why does the device have two MS-Organization-Access certificates?
Re-enrollment leaves the previous certificate in place until something cleans it up. The script handles this explicitly by evaluating the certificate with the latest NotAfter as the current one and logging the older one as context, so an expired leftover never triggers a false alarm.
What warning window should I use?
Thirty days is a sensible default for weekly detection. If your re-enrollment process is slow, or devices go offline for long stretches by design, widen the window and increase the frequency so you always have more lead time than your slowest recovery path.
Comments
0No comments yet — be the first to share your thoughts.