Proactive Admin Auditing in Intune: Building a Continuous Compliance Detection Framework
Most organizations discover unauthorized administrative access weeks or months after it occurs—if they discover it at all. By then, attackers may have already leveraged that access to escalate privileges, move laterally across your network, and compromise sensitive data. This article shows you how to deploy a continuous compliance detection framework that catches unauthorized local admin access in hours, not weeks.
The Security Gap: Why Reactive Admin Auditing Fails
Local administrator accounts represent the highest-value target in any Windows environment. A single compromised admin account grants unrestricted access to system configuration, security controls, device encryption keys, and sensitive data. Yet in many Intune-managed environments, there is no continuous detection mechanism running on endpoints—only periodic audits that lag reality by days or weeks.
The Hidden Risk: Every day without continuous admin auditing is a day where unauthorized privilege escalation could go undetected. By the time a manual audit discovers the violation, attackers have hours or days to move laterally across your network. Proactive remediation policies in Intune change this equation by deploying detection scripts that run silently on every managed device on a defined schedule.
Understanding the Detection Architecture
The audit flow follows a cloud-to-endpoint-to-cloud pattern that creates a closed-loop security control:
- Cloud Policy Deployment: Your Intune tenant publishes a proactive remediation policy containing detection and optional remediation scripts.
- Endpoint Execution: The Intune Management Extension (IME) on each Windows device executes the detection script in a SYSTEM context on your defined schedule.
- Compliance Reporting: Script output (compliant/non-compliant) flows back to Intune's compliance engine and feeds your dashboards, alerts, and audit logs.
- Centralized Visibility: Security teams view compliance status across the entire fleet in real-time, filter by non-compliance, and trigger incident response workflows.
The Detection Logic: A Three-Step Process
The core logic is straightforward but powerful. Your detection script runs through three sequential phases:
Step 1: Identify the Logged-In User
Query the Win32_ComputerSystem WMI class to retrieve the currently interactive user. This returns a string in the format DOMAIN\USERNAME or COMPUTERNAME\USERNAME for local accounts.
Step 2: Query Local Group Membership
Use the net localgroup Administrators command to enumerate all members of the local Administrators group. This includes domain accounts, local accounts, and domain groups. The output is parsed to extract usernames.
Step 3: Perform Membership Comparison
Compare the logged-in user against the list of group members. Account for domain prefixes, escaped special characters, and localized group names (Administrators in English, Administrateurs in French, etc.). Return compliant if the user is not an admin, non-compliant if they are.
PowerShell Implementation
Below is a production-ready detection script with improved error handling and robustness:
# Proactive Remediation: Local Admin Detection
# Execution Context: SYSTEM
# Purpose: Identify if logged-in user holds local admin privileges
try {
# Get the currently logged-in (interactive) user
$loggedInUser = (Get-WmiObject -Class Win32_ComputerSystem -ErrorAction Stop).UserName
if ([string]::IsNullOrWhiteSpace($loggedInUser)) {
Write-Output "COMPLIANT: No user currently logged in."
exit 0
}
# List of possible admin group names (multi-language support)
$adminGroups = @("Administrators", "Administrateurs", "Administratoren")
$isAdmin = $false
$foundGroup = $null
foreach ($group in $adminGroups) {
try {
$members = net localgroup "$group" 2>$null
if ($members) {
# Escape regex special characters and match against members
$escapedUser = [regex]::Escape($loggedInUser)
if ($members -match "^\s*$escapedUser\s*$") {
$isAdmin = $true
$foundGroup = $group
break
}
}
} catch {
# Continue to next group if current group query fails
continue
}
}
# Output result in Intune-compliant format
if ($isAdmin) {
Write-Output "NON_COMPLIANT: User '$loggedInUser' holds admin rights in group '$foundGroup'."
exit 1
} else {
Write-Output "COMPLIANT: User '$loggedInUser' does not hold admin privileges."
exit 0
}
} catch {
Write-Output "ERROR: Detection script failed - $_"
exit 1
}
Technical Improvements Over the Original Script
| Improvement | Details | Impact |
|---|---|---|
| Exit Codes | Uses proper exit codes (0 = compliant, 1 = non-compliant) | Intune's compliance engine parses exit codes; ambiguous outputs break detection |
| Error Handling | Wrapped in try-catch with fail-safe exit 1 | Prevents script failures from returning ambiguous results; treat errors as violations |
| Multi-Language | Includes German (Administratoren) in addition to English and French | Detection works across localized Windows installations worldwide |
| Regex Anchors | Uses ^\s*...$ to prevent partial matches |
Prevents false positives (e.g., matching "admin" within "administrator") |
| Null Safety | Checks for null or whitespace logged-in user before processing | Gracefully handles scenarios where no user is interactively logged in |
Deployment in Intune
Creating the Proactive Remediation Policy
Navigate to Remediation Settings
In the Microsoft Intune admin center, go to Devices → Windows → Remediation (or Windows Remediation depending on your portal version).
Create Script Package
Click Create script package. Fill in the basic details:
- Name: "Local Admin Detection - Continuous Audit"
- Description: "Proactive detection of unauthorized local admin access. Runs hourly on all managed Windows devices."
Paste Detection Script
Copy the PowerShell detection script above into the Detection script field. Leave the Remediation script empty unless you want automatic remediation (not recommended initially).
Set Execution Context to SYSTEM
Set Run this script using the logged-in credentials to No. The script must execute in SYSTEM context to query group membership reliably.
Configure Script Signing (Optional for Testing)
Set Enforce script signature check to No for initial testing. Once validated, sign scripts with an organizational certificate and enable this setting in production.
Review and Save
Review all settings, then click Create to save the policy.
Assignment and Scheduling
Assign the policy to a security group containing your target devices. For broad coverage, use a group like "All Company Windows Devices" or segment by risk profile (e.g., "High-Sensitivity Departments").
Set the execution schedule:
| Schedule | Frequency | Use Case | Resource Impact |
|---|---|---|---|
| Every 24 hours | Daily | Most organizations; standard compliance verification | Minimal (one script run per day) |
| Every 6 hours | 4× daily | High-security environments; sensitive data departments | Low (light CPU & network per execution) |
| Every 1 hour | 24× daily | Incident response; short-term intensive monitoring only | High (significant CPU, network, and disk I/O) |
Monitoring and Alert Strategy
Compliance Dashboard
Navigate to Devices → Remediation and select your policy. The overview card shows overall compliance percentage. Click through to see device-level status:
- Compliant: Logged-in user is not an administrator (expected state).
- Non-Compliant: Logged-in user holds admin privileges (requires investigation).
- Not Applicable: Device didn't run the script (offline, policy not assigned, etc.).
- Error: Script execution failed (check Intune Management Extension logs at
C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\).
Alert Configuration
| Alert Method | Detection Speed | Best For | Status |
|---|---|---|---|
| Intune Native Alerts | Low ✓ (every 30 min) | Small to medium organizations; simple threshold alerts | ✓ Recommended |
| Microsoft Sentinel KQL | Medium ✓ (minutes) | Large organizations; correlation with other security events; anomaly detection | ✓ Recommended |
| Logic Apps / Webhooks | Medium ✓ (seconds) | Automated response workflows; ticketing system integration; custom escalation | ✓ Recommended |
Graph API for Advanced Reporting
For deeper integration and programmatic access, query Intune's compliance data via the Microsoft Graph API:
# Get all proactive remediation policies
GET https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies
# Get non-compliant devices for a specific policy
GET https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies/{policyId}/deviceStatuses?$filter=status eq 'noncompliant'
# Create a subscription to stream real-time compliance changes (new in v2.0)
POST https://graph.microsoft.com/beta/subscriptions
{
"changeType": "updated",
"notificationUrl": "https://your-webhook-endpoint.com/intune-compliance",
"resource": "/deviceManagement/deviceCompliancePolicies/YOUR_POLICY_ID/deviceStatuses",
"expirationDateTime": "2025-12-31T23:59:00Z"
}
# Get detailed compliance status for a specific device
GET https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies/{policyId}/deviceStatuses/{deviceId}
These endpoints enable you to:
- Build custom dashboards that refresh in real-time
- Export compliance history for audit reports
- Correlate Intune compliance with Azure AD sign-in data or Sentinel logs
- Automate remediation workflows triggered by policy changes
DeviceManagementServiceConfig.ReadWrite.All scope. Use client credentials (service principal) for unattended automation, or delegated permissions (user login) for interactive dashboards.
Security Considerations
Execution Context and Privileges
The script runs in SYSTEM context, which is necessary to query the local Administrators group. However, this also means any vulnerability in the script logic could be leveraged for privilege escalation. Harden against this:
- Code Sign: Sign your detection scripts with an organizational certificate and enable signature validation in the policy settings.
- Version Control: Store scripts in a source control system (Azure Repos, GitHub) with pull request review gates before deployment.
- Audit Execution: Monitor IME logs (
C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\) for unexpected script behavior or repeated errors.
False Positives and Service Accounts
Some scenarios will legitimately result in non-compliance:
- Service Accounts: If your organization uses local admin service accounts that must stay logged in (for backup software, monitoring agents, etc.), those devices will perpetually non-comply. Consider a separate policy for those devices or adjust your baseline to exclude approved service accounts from the detection logic.
- Temporary Admin Access: During incident response or maintenance, admins may need temporary local admin rights. Communicate with your security team to ensure non-compliance alerts are context-aware. Integrate with Azure Privileged Identity Management (PIM) to document approved temporary elevations.
Remediation Without Approval
The script above only detects. Adding a remediation script that automatically removes users from the Administrators group is possible but dangerous:
# WARNING: Automatic remediation can lock out legitimate admins
# Only deploy after extensive testing and approval workflows
Remove-LocalGroupMember -Group "Administrators" -Member $loggedInUser -ErrorAction SilentlyContinue
Unless you have robust controls to prevent accidental mass-removal, keep detection and remediation separate. Use detection to identify violations, then use approval-based workflows (Intune Endpoint Privilege Management, Azure Privileged Identity Management) to manage admin access.
Extending the Framework
Once baseline detection is working, consider expansions to broaden your security visibility:
- Privilege Access Workstations (PAWs): Exempt critical admin devices from this policy and instead audit via a separate, hardened remediation track.
- Group Membership Audit: Expand the script to check membership in other privileged groups (Remote Desktop Users, Power Users, Device Administrators).
- Account Age Detection: Flag administrator accounts created in the last 7 days (potential unauthorized account creation).
- Failed Login Attempts: Parse Windows Event Log (Event ID 4625) for failed admin account login patterns, indicating brute-force attacks.
- Sentinel Analytics: Feed non-compliance data into Sentinel's UEBA (User and Entity Behavior Analytics) to detect anomalies in access patterns and correlate with external threat intelligence.
Key Takeaways
Proactive remediation transforms admin auditing from a periodic compliance checkbox into a continuous security control. By deploying PowerShell detection scripts through Intune on a regular schedule, you achieve:
- Real-Time Visibility: Know within hours (not weeks) when unauthorized admin access occurs. Reduce incident response time from days to hours; limit breach window.
- Scalable Audit: Monitor thousands of devices simultaneously without manual intervention. Eliminate manual audits; free security team for higher-value work.
- Audit Trail: Maintain compliance evidence through automated reporting and centralized logging. Pass regulatory audits; prove continuous monitoring to compliance teams.
- Incident Response Integration: Trigger automated or manual remediation workflows immediately upon detection. Orchestrate response across ticketing, SIEM, and access control systems.
Recommended Implementation Roadmap
- Week 1–2 (Test) Deploy detection-only script to pilot group (50–100 IT devices). Validate against your security baselines.
- Week 3–4 (Pilot) Expand to one non-critical department (500 devices). Set up dashboards and alerting. Train security team on triage workflows.
- Week 5–6 (Harden) Enable code signing, set up Sentinel integration, document approved exceptions (service accounts, PAWs).
- Week 7+ (Production) Roll out to entire organization. Monitor for 2–4 weeks before enabling any auto-remediation. Iterate on alert thresholds based on observed patterns.