/
/

How to Automate Threat Response with Conditional Access, Graph, and PowerShell

by Grant Funtila, Technical Writer
How to Automate Threat Response with Conditional Access, Graph, and PowerShell blog banner image
How to Automate Threat Response with Conditional Access, Graph, and PowerShell blog banner image

Manually responding to identity-based threats wastes time and may lead to increased risk exposure. You may be leaking sensitive data, putting your organization at risk. One way to increase protection is to integrate Microsoft Conditional Access (CA) with Graph API triggers and PowerShell automation, which results in automated threat response.

This lets MSPs (Managed Services Providers) contain and mitigate threats without relying on expensive SIEM (Security Information and Event Management) platforms.

Automating threat responses using Conditional Access, Microsoft Graph, and PowerShell

There are different ways to automate threat responses. You can configure Conditional Access policies, use Microsoft Graph, make a PowerShell script, track threat response events in the Registry, and use GPO to enforce quarantine behavior.

📌 Prerequisites:

  • Azure AD Premium P2 for Identity Protection and Conditional Access
  • Microsoft Defender for Endpoint or an equivalent risk-based signal source
  • Microsoft Graph API permissions
  • PowerShell 7+ with Microsoft.Graph module installed

📌 Recommended deployment strategies:

Click to Choose a Method

💻

Best for Individual Users

💻💻💻

Best for Enterprises

Method 1: Configure Conditional Access policies for threat response
Method 2: Use Microsoft Graph to trigger real-time policy actions
Method 3: Automate remediation using PowerShell
Method 4: Track threat response events in the Registry
Method 5: Use GPO to enforce quarantine behavior on risky devices

Method 1: Configure Conditional Access policies for threat response

The first step is to configure Conditional Access policies.

📌 Use Case: IT admins creating Conditional Access rules that automatically block or challenge risky sign-ins

Create Conditional Access policies in Entra ID for threat signals:

  • User risk-based response:
    • Signal: UserRiskLevel = High
    • Action: Block access or require a password reset
  • Device risk-based response:
    • Signal: DeviceRiskLevel = High (from Defender)
    • Action: Require a compliant device or block access

Example policy filter expression:

(device.deviceOwnership -eq “Company”) and (device.riskLevel -eq “High”)

Assign policies to risk-prone roles, such as admins and executives.

⚠️ Warning: Restrictive rules may lock out admins and other legitimate users. (For more info, refer to: Things to look out for)

Method 2: Use Microsoft Graph to trigger real-time policy actions

You can use Microsoft Graph to trigger real-time policy actions.

📌 Use Case: IT admins building a script that queries risky users and disables their accounts in real time

  1. Press Win, type PowerShell, then click Run as administrator.
  2. Copy and paste the following scripts into the prompt, then press Enter:
Connect-MgGraph -Scopes “User.ReadWrite.All”, “IdentityRiskEvent.Read.All”

$riskyUsers = Get-MgRiskyUser | Where-Object { $_.RiskLevel -eq “high” -and $_.RiskState -eq “atRisk” }

foreach ($user in $riskyUsers) {

Update-MgUser -UserId $user.Id -AccountEnabled:$false

Write-Output “Disabled account: $($user.UserPrincipalName)”

}

💡 Tip: Log the action and optionally notify an admin or open a PSA ticket to ensure visibility for security teams.

Method 3: Automate remediation using PowerShell

You can use PowerShell to turn risk detections into repeatable, auditable actions.

📌 Use Case: IT admins automating account recovery by forcing password resets, invalidating tokens, and quarantining devices after high-risk detections

For example, you can reset MFA (Multi-Factor Authentication) and trigger a password reset using PowerShell.

  1. Press Win, type PowerShell, then click Run as administrator.
  2. Copy and paste the following scripts into the prompt, then press Enter:
Connect-MgGraph -Scopes “User.ReadWrite.All”, “IdentityRiskyUser.ReadWrite.All”, “Device.ReadWrite.All”

$riskyUsers = Get-MgRiskyUser | Where-Object { $_.RiskLevel -eq “high” -and $_.RiskState -eq “atRisk” }

foreach ($user in $riskyUsers) {

try {

# Invalidate all active sessions

Invoke-MgInvalidateUserRefreshToken -UserId $user.Id

# Force password reset on next sign-in (requires a temporary password)

$tempPassword = “TempP@ssw0rd!” # Replace with a secure generator if needed

Update-MgUser -UserId $user.Id -PasswordProfile @{

Password = $tempPassword

ForceChangePasswordNextSignIn = $true

}

# Quarantine associated device(s) if extension attribute exists

$devices = Get-MgUserRegisteredDevice -UserId $user.Id

foreach ($device in $devices) {

try {

Update-MgDevice -DeviceId $device.Id -AdditionalProperties @{

“extensionAttribute1” = “Quarantined”

}

} catch {

Write-Warning “Failed to update device $($device.Id)”

}

}

Write-Output “Remediated: $($user.UserPrincipalName)”

} catch {

Write-Warning “Failed to remediate user $($user.UserPrincipalName)”

}

}

  • Quarantine device by tag or policy filter:
Update-MgDevice -DeviceId $device.Id -AdditionalProperties @{ “extensionAttribute1” = “Quarantined” }

💡 Tip: You can combine these scripts with RMM tasks or trigger via email alerts and Logic Apps.

⚠️ Warning: Before deploying the settings change on different endpoints, it’s best to test it out on a local machine first. (For more info, refer to: Things to look out for)

Method 4: Track threat response events in the Registry

This method logs local response events in the registry for devices not covered by Microsoft Defender or Intune.

📌 Use Case: IT admins logging threat response activity in the Windows registry to maintain local audit trails

  1. Press Win, type PowerShell, then click Run as administrator.
  2. Copy and paste the following scripts into the prompt, then press Enter:
New-Item -Path “HKLM:\SOFTWARE\Org\ThreatResponse” -Force

Set-ItemProperty -Path “HKLM:\SOFTWARE\Org\ThreatResponse” `

-Name “LastResponse” -Value “$(Get-Date) – Quarantine enforced”

Set-ItemProperty -Path “HKLM:\SOFTWARE\Org\ThreatResponse” `

-Name “QuarantineState” -Value “True”

You can also check what’s inside the registry key by copy-pasting the following prompt:

reg query HKLM\SOFTWARE\Org\ThreatResponse

⚠️ Warning: Editing the registry can have unintended consequences. Proceed with caution and back up the registry before making changes. (For more info, refer to: Things to look out for)

Method 5: Use GPO to enforce quarantine behavior on risky devices

You can use GPO to enforce restrictions when local registry keys indicate quarantine.

📌 Use Case: IT admins enforcing endpoint quarantine by disabling internet access and applications when the registry indicates a quarantined state

📌 Prerequisite: GPO access for local quarantine policies

  1. Press Win + R, type gpmc.msc, then press Enter.
  2. Navigate the following path:
    • Computer Configuration > Windows Settings > Security Settings > Software Restriction Policies

In this example, you can restrict access to mapped drives or block internet browsers.

You can also check a quarantine flag in the registry and act on the endpoint. To do so, run the following script in PowerShell:

Script logic (triggered by key):

if ((Get-ItemPropertyValue -Path “HKLM:\SOFTWARE\Org\ThreatResponse” -Name “QuarantineState”) -eq “True”) {

Stop-Process -Name “chrome” -Force

Disable-NetAdapter -Name “Wi-Fi” -Confirm:$false

}

⚠️ Things to look out for

RisksPotential ConsequencesReversals
Restrictive rules may block legitimate usersAdmins may get locked out.Disable/delete policy in Entra ID.
Not testing on a local machineDeploying an untested script may cause devices to crash due to issues such as registry key incompatibility.Apply the changes you want on a local machine, and then verify if the configuration reflects the intended results.
Editing the Registry without backupIncorrectly editing the registry could result in corruption, so it’s best to make a backup beforehand.Export the registry key before changes by pressing File > Export.

Additional considerations

To build resilient identity protections, organizations should focus on precise targeting, clear escalation paths, multi-tenant visibility, and careful validation of threat signals.

Scope filters

Avoid applying CA policies that affect non-threatened users since they can cause disruption. For example, you may accidentally lock out administrators or service accounts if you enforce a strict block policy. To prevent this, you may use groups, attributes, or administrative units to target CA policies to only high-risk groups.

Escalation paths

Some signals can be ignored without an escalation process, or critical alerts could block users without remediation. You can implement ticketing integration for follow-up and investigation. This involves routing high-risk sign-ins, blocking access attempts, or directly incorporating identity protection risk detections into a ticketing system.

Cross-tenant alerting

Visibility across environments makes it difficult for MSPS to manage multiple tenants. Consider Graph API loops or Logic Apps for better cross-tenant monitoring:

  • Graph API loops: Poll Microsoft Graph across each managed tenant to collect alert and sign-in data.
  • Logic apps: Automate the collection and forwarding of alerts to a central SIEM.

Threat signal validation

CA can enforce policy based on Microsoft Defender, Entra ID, and Identity Protection signals. However, false positives still happen, and implementing based on these signals can result in unnecessary lockouts. One way to prevent these lockouts is by requiring more than one risk signal before triggering a block.

Troubleshooting common issues

The following are common issues you may face when automating threat responses, and how to resolve them.

Graph errors

If you’re running into Graph errors, confirming delegated and app token permissions is ideal. Decode both the delegate and app tokens while looking for patterns. 401 patterns refer to token issues, while 403 represents insufficient permission.

Policy delays

Graph-based updates may take minutes to apply, so it’s best to use sign-in logs to confirm. Auditing the logs and verifying that your Graph change has been completed is also ideal.

GPO not triggering

Check the policy refresh cadence and script run context if the GPO isn’t triggering. You can also force a refresh by running gpupdate /force.

NinjaOne services that support automated threat response

MSPs can scale response workflows in hybrid and non-Microsoft-native environments using NinjaOne. NinjaOne services support automated threat response by:

  • Deploying scripts to isolate or tag compromised devices
  • Monitoring registry keys and risk indicators to trigger remediation
  • Tagging endpoints for policy assignment
  • Triggering alerts and workflow automation based on script results
  • Reporting across tenants on threat response events, actions taken, and affected endpoints

Reduce dwell time during compromise by automating threat response

Automating threat response with Microsoft Conditional Access, Graph API, and PowerShell helps MSPs contain risks without expensive SIEM tools. You can also use tools like NinjaOne to enhance automation by deploying scripts, monitoring endpoints, and streamlining cross-tenant visibility and reporting.

Related topics:

You might also like

Ready to simplify the hardest parts of IT?