← Back to articles PowerShell

Proactive Admin Auditing in Intune: Building a Continuous Compliance Detection Framework

Proactive Admin Auditing in Intune: Building a Continuous Compliance Detection Framework

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.

Production Requirement This guide assumes you have Intune management of Windows 10/11 devices and the Intune Management Extension (IME) deployed. All detection scripts run in SYSTEM context and require code review and approval before enterprise rollout.

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.

The Shift to Proactive Security Shifting from incident response to continuous compliance verification means the moment an unauthorized user gains admin privileges, your infrastructure knows. Your security team gets alerted. You respond in hours, not weeks.

Understanding the Detection Architecture

INTUNE Policy Deployment DEVICE 1 Execute Detection DEVICE N Execute Detection Compliance Engine Report Status Dashboard & Alerts ✓ OK Compliant ✗ Alert Non-Compliant Security Team Incident Response Deploy / Remediate CLOSED-LOOP AUDIT FLOW
Cloud-to-endpoint audit flow: Intune publishes policy → devices execute detection → compliance reports flow back → dashboards trigger alerts → security team responds in a closed-loop pattern.

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

DETECTION PROCESS Step 1 Query Logged-In User Win32_ComputerSystem Returns: DOMAIN\USERNAME Step 2 Query Local Admin Group Members net localgroup Returns: List of all members Step 3 Compare & Decide Is logged-in user in admin list? NO: exit 0 ✓ COMPLIANT User is not admin No action required YES: exit 1 ✗ NON-COMPLIANT User IS admin Violation detected Error ERROR All comparisons account for domain prefixes, multi-language group names, and special character escaping
Three-step detection process: (1) identify the currently logged-in user, (2) enumerate admin group members, (3) compare and return compliance status.

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.

Pro Tip: Staged Rollout Start with a pilot group of 50–100 devices in your IT department or a non-critical department. Monitor for 1–2 weeks before expanding to the entire organization. This allows you to validate the detection logic, adjust alert thresholds, and train your security team on the expected non-compliance patterns.

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)
Caution: Do Not Over-Schedule Running detection every 15 minutes on thousands of devices will strain your Intune infrastructure and endpoint networks. Even "every 1 hour" should only be temporary during active incident response. Default to daily (24-hour) schedules for sustainable operations.

Monitoring and Alert Strategy

COMPLIANCE DASHBOARD Local Admin Detection - Continuous Audit COMPLIANT User is not admin Desired state achieved No action needed 4,250 devices NON-COMPLIANT User IS admin Violation detected Requires investigation 18 devices ERROR / OFFLINE Script failed or device offline Check IME logs or connectivity 32 devices OVERALL 98.5% compliant NEXT STEPS FOR NON-COMPLIANT DEVICES 1 Identify Violation Click on non-compliant device to view which user holds admin rights First device: CORP\jsmith 2 Investigate Context Is this a legitimate admin? A service account? An unauthorized escalation? 3 Remediate or Document Remove from admin group, or document as approved exception in your baseline 4 Re-run Detection Re-run detection after remediation (or wait for next scheduled execution) Navigate to Devices → Remediation and select your policy to view this dashboard.
Compliance dashboard shows four device status categories: compliant (user is not admin), non-compliant (user is admin), error/offline (detection did not run), and overall compliance percentage.

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
Recommended Approach: Sentinel + Logic Apps Stream Intune compliance data to Microsoft Sentinel using the Intune connector. In Sentinel, create a KQL query to detect non-compliance patterns (e.g., "same device non-compliant 3 times in 24 hours"). Use a playbook (Logic App) to automatically create an incident, notify your security team via Teams, and optionally disable the user account pending review.

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
Authentication Required All Graph API calls require an Azure AD app registration with the 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.
SECURITY HARDENING CHECKLIST ✓ Code Signing Sign detection scripts with org cert Enable sig validation in policy Prevents tampering or injection RECOMMENDED ✓ Version Control & Review Store in Azure Repos or GitHub Require pull request reviews Audit all script changes RECOMMENDED ✓ Audit IME Logs Monitor C:\ProgramData\ Microsoft\... Alert on repeated errors or timeouts Escalate anomalies to SecOps RECOMMENDED ⚠ Avoid Auto- Remediation Detection-only prevents accidents Manual = controlled risk Use PAM for admin access CRITICAL ⚠ Production Deployment Requirement All four items above are mandatory before deploying to production. Start with detection-only in test/pilot, then harden before enterprise rollout. Never enable auto-remediation without extensive approval workflows and rollback procedures.
Security hardening checklist: code signing, version control, log auditing, and detection-only (no auto-remediation) are required for production deployments.

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

EXTENSION STRATEGY Local Admin Detection (Baseline) PAW Hardening Exempt/isolate privileged admin workstations from this policy Separates privileged access Expanded Group Audit Check RDP Users, Power Users, DeviceAdmins, more Broader privilege coverage Account Age Detection Flag admin accounts created within last 7 days Catches unauthorized creation Failed Login Monitoring Parse Event Log 4625 Detect brute-force attempts Attack detection in progress Sentinel UEBA & Analytics Feed compliance data; detect anomalies Advanced correlation IMPLEMENTATION TIMELINE Week 1–4 Baseline detection working and validated Week 5–8 Add PAW hardening + expanded group audit for high-risk departments
Expansion strategy: baseline local admin detection feeds into multiple specialized detection modules for PAWs, broader group membership, account age, failed logins, and Sentinel analytics.

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

  1. Week 1–2 (Test) Deploy detection-only script to pilot group (50–100 IT devices). Validate against your security baselines.
  2. Week 3–4 (Pilot) Expand to one non-critical department (500 devices). Set up dashboards and alerting. Train security team on triage workflows.
  3. Week 5–6 (Harden) Enable code signing, set up Sentinel integration, document approved exceptions (service accounts, PAWs).
  4. 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.
Start Small, Scale Responsibly Start with detection-only scripts in your test environment, validate against your security baselines, then roll out to production with appropriate monitoring and alerting. The investment in this framework pays dividends the first time you catch unauthorized admin access before it becomes a breach.

Was this article helpful?

🎓 Ready to go deeper?

Practice real MD-102 exam questions, get AI feedback on your weak areas, and fast-track your Intune certification.

Start Free Practice → Book a Session
Souhaiel Morhag
Souhaiel Morhag
Microsoft Endpoint & Modern Workplace Engineer

Souhaiel Morhag is a Microsoft Intune and endpoint management specialist with hands-on experience deploying and securing enterprise environments across Microsoft 365. He founded MSEndpoint.com to share practical, real-world guides for IT admins navigating Microsoft technologies — and built the MSEndpoint Academy at app.msendpoint.com/academy, a dedicated learning platform for professionals preparing for the MD-102 (Microsoft 365 Endpoint Administrator) certification. Through in-depth articles and AI-powered practice exams, Souhaiel helps IT teams move faster and certify with confidence.

Related Articles

Popular on MSEndpoint