This document provides the script I use to monitor out of hour phishing emails in Defender XDR. This is done by using KQL through PowerShell which compiles the data to SharePoint. A Copilot agent then summaries the data to produce a report each morning. This process authenticates through MS Graph so certain aspects of the authentication process have been redacted from the script.
==========================
Defender Device Health Export – Daily Export Script
==========================
$BaseOutputFolder = “C:\Data\Phishing Emails Folder”
$DateStamp = Get-Date -Format “yyyy-MM-dd”
$OutputFolder = $BaseOutputFolder
#$DateStamp
if (!(Test-Path $OutputFolder))
{
New-Item -ItemType Directory -Path $OutputFolder -Force | Out-Null
}
Write-Host “Authenticating to Graph…” – REDACTED
try
{
$TokenResponse = Invoke-RestMethod -Method POST
-Uri https://login.microsoftonline.com/……………
-Body $TokenBody
}
catch
{
Write-Error “Authentication failed.”
throw
}
$Headers = @{
Authorization = “Bearer $AccessToken”
“Content-Type” = “application/json”
}
Function – Run Hunting Query
function Invoke-HuntingQuery
{
param(
[string]$Query
)
$Body = @{
Query = $Query
} | ConvertTo-Json -Depth 5
$Results = Invoke-RestMethod -Method POST
-Uri “https://graph.microsoft.com/v1.0/security/runHuntingQuery” -Headers $Headers
-Body $Body
return $Results.results
}
Query – Phishing Query
Write-Host “Running Out of Hours Phishing Query…”
$PhishingQuery = @”
EmailEvents
| where Timestamp > ago(24h)
| where ThreatTypes has “Phish”
| where DeliveryAction in (“Blocked”,”Quarantine”)
| extend HourOfDay = datetime_part(“Hour”, Timestamp)
| where HourOfDay >= 18 or HourOfDay < 6
| extend SenderDomain = tostring(split(SenderFromAddress, “@”)[1])
| summarize
Emails=count(),
Recipients=dcount(RecipientEmailAddress)
by SenderDomain
| sort by Emails desc
| limit 20
“@
$PhishingQuery = Invoke-HuntingQuery -Query $PhishingQuery
Remove Defender OData metadata columns
$PhishingQueryClean = $PhishingQuery |
Select-Object SenderDomain, Emails, Recipients
$PhishingQueryClean |
Export-Csv "$OutputFolder\Phishing_Emails.csv"
-NoTypeInformation
Once queries are completed
Write-Host “”
Write-Host “=====================================”
Write-Host “Export Complete”
Write-Host “=====================================”
Write-Host “”
Write-Host “Output Folder:”
Write-Host $OutputFolder
Write-Host “”
Write-Host “Files Created:”
Write-Host ” – PhishingQuery.csv”
==========================
Copilot Agent Creation
==========================
Here’s a summary of the agent creation process:
- Collect the Data
- Export out-of-hours phishing email statistics to a CSV file containing sender domains, email counts, and recipient counts.
- Store the file in the Cyber Security SharePoint phishing repository.
- Create a Copilot Agent
- Create a new agent in Microsoft Copilot Studio.
- Name: Out Of Hours Phishing Emails.
- Add a Knowledge Source
- Connect the SharePoint location containing the phishing email reports and CSV datasets.
- Define Agent Instructions
- Tell the agent to:
- Analyse phishing trends and identify items that may require further investigation.
- Tell the agent to:
- Configure the Analysis
- Review:
- The agent reviews the dataset for patterns and indicators that may warrant additional analyst investigation.
- Review:
- Generate Outputs
- Executive summary.
- Key findings.
- Investigation priorities.
- Recommended actions.
- Use for Ongoing Monitoring
- Upload or refresh the phishing dataset regularly.
- Let the agent automatically produce threat intelligence summaries and campaign analysis. The data source file identified in the repository.
This provides a lightweight phishing intelligence assistant that transforms raw email statistics into actionable security insights.
