Forum Discussion

GrahamP67's avatar
GrahamP67
Copper Contributor
Apr 20, 2023

Defender Advanced Hunting with PowerShell

I am trying to write a PS script that runs a query in Defender Adavanced Hunting to get details from the EmailAttachmentInfo schema. I have registered an App, assigned the permission WindowsdefenderATP AdavancedQuery.Read.All  and am able to generate a token and authenticate.

 

When I run this simple query 'EmailAttachmentInfo | limit 10' I get a 400 Error.

Changing the the query to 'DeviceRegistryEvents | limit 10' returns data.

 

Are there additional permissions I need to assign the App in AAD to see the EmailAttachmentInfo schema?

 

Oddly when I log in to Defender 365 console I can see and query the EmailAttachmentInfo schema but cant see DeviceRegistryEvents.

 

Code below 

$tenantId = 'redacted' # Paste your own tenant ID here
$appId = 'redacted' # Paste your own app ID here
$appSecret = 'redacted' # Paste your own app secret here
$resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
$oAuthUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$body = [Ordered] @{
    resource = "$resourceAppIdUri"
    client_id = "$appId"
    client_secret = "$appSecret"
    grant_type = 'client_credentials'
}
$response = Invoke-RestMethod -Method Post -Uri $oAuthUri -Body $body -ErrorAction Stop
$aadToken = $response.access_token

$query = 'EmailAttachmentInfo | limit 10' # Paste your own query here
$url = "https://api.securitycenter.microsoft.com/api/advancedqueries/run"
$headers = @{ 
    'Content-Type' = 'application/json'
    Authorization = "Bearer $aadToken" 
}
$body = ConvertTo-Json -InputObject @{ 'Query' = $query }
$webResponse = Invoke-WebRequest -Method Post -Uri $url -Headers $headers -Body $body -ErrorAction Stop
$response =  $webResponse | ConvertFrom-Json
$results = $response.Results
$schema = $response.Schema

 

Resources