Paste these into Logs in Microsoft Sentinel or Log Analytics, Advanced hunting in Microsoft Defender, or Azure Data Explorer. KQL is case-sensitive for table names, column names and operators. Sentinel and Log Analytics use TimeGenerated for the time column; Defender advanced hunting tables (the ones starting Device and Email) use Timestamp, so swap it in there. Table and column names depend on which data connectors you have, and user names, addresses and thresholds are examples, so swap in your own.
Official links: Kusto Query Language overview, KQL for Microsoft Sentinel.
Basics #
-
Show 10 rows from a tableKQL
SecurityEvent | take 10 -
Count the rows in a tableKQL
SecurityEvent | count -
Show the columns and types in a tableKQL
SecurityEvent | getschema -
Search every table for a wordKQL
search "mimikatz" -
Search some tables for a wordKQL
search in (SecurityEvent, Syslog) "mimikatz" -
List the tables that have data in the last dayKQL
union withsource=TableName * | where TimeGenerated > ago(1d) | summarize Rows = count() by TableName | sort by Rows desc -
Add a commentKQL
// This line is ignored -
Name a value to reuseKQL
let lookback = 7d; SecurityEvent | where TimeGenerated > ago(lookback) -
Name a list to reuseKQL
let admins = dynamic(["admin", "administrator", "root"]); SigninLogs | where UserPrincipalName has_any (admins)
Time #
-
Last 24 hoursKQL
SecurityEvent | where TimeGenerated > ago(24h) -
Last 7 daysKQL
SecurityEvent | where TimeGenerated > ago(7d) -
Between two datesKQL
SecurityEvent | where TimeGenerated between (datetime(2026-11-01) .. datetime(2026-11-08)) -
Today onlyKQL
SecurityEvent | where TimeGenerated > startofday(now()) -
Newest firstKQL
SecurityEvent | sort by TimeGenerated desc -
Group into hourly bucketsKQL
SecurityEvent | where TimeGenerated > ago(1d) | summarize count() by bin(TimeGenerated, 1h) -
Show times in another time zoneKQL
SecurityEvent | extend LocalTime = datetime_utc_to_local(TimeGenerated, 'Europe/Dublin') -
Format a date as textKQL
SecurityEvent | extend Day = format_datetime(TimeGenerated, 'yyyy-MM-dd') -
Work out how long ago something happenedKQL
SecurityEvent | extend Age = now() - TimeGenerated -
Start of the weekKQL
SecurityEvent | where TimeGenerated > startofweek(now()) -
Day of the week (0 is Sunday)KQL
SecurityEvent | extend Day = dayofweek(TimeGenerated) / 1d -
Hour of the dayKQL
SecurityEvent | extend Hour = hourofday(TimeGenerated) -
Out-of-hours activity (before 7am or after 7pm)KQL
SigninLogs | where hourofday(TimeGenerated) < 7 or hourofday(TimeGenerated) >= 19 -
Minutes between two timesKQL
SigninLogs | summarize First = min(TimeGenerated), Last = max(TimeGenerated) by UserPrincipalName | extend Minutes = datetime_diff('minute', Last, First) -
A window in the past (8 to 1 days ago)KQL
SecurityEvent | where TimeGenerated between (ago(8d) .. ago(1d))
Filtering #
-
Exact match (case-sensitive)KQL
SecurityEvent | where Computer == "web01" -
Exact match, ignoring caseKQL
SecurityEvent | where Computer =~ "web01" -
Not equalKQL
SecurityEvent | where Computer != "web01" -
Contains a whole word (fast)KQL
SecurityEvent | where CommandLine has "mimikatz" -
Contains any text (slower)KQL
SecurityEvent | where CommandLine contains "mimikatz" -
Contains any of several wordsKQL
SecurityEvent | where CommandLine has_any ("mimikatz", "procdump", "lsass") -
Starts withKQL
SecurityEvent | where Computer startswith "web" -
Matches a regular expressionKQL
SecurityEvent | where Computer matches regex @"^web\d+$" -
Is one of a list, ignoring caseKQL
SecurityEvent | where Computer in~ ("web01", "web02") -
Isn't one of a listKQL
SecurityEvent | where Computer !in ("web01", "web02") -
Has a value (not empty)KQL
SecurityEvent | where isnotempty(Computer) -
Combine conditionsKQL
SecurityEvent | where EventID == 4625 and Account !endswith "$" -
Address is in a subnetKQL
SigninLogs | where ipv4_is_in_range(IPAddress, "10.0.0.0/8") -
Address is privateKQL
CommonSecurityLog | where ipv4_is_private(SourceIP)
Text and numbers #
-
Lower caseKQL
SigninLogs | extend User = tolower(UserPrincipalName) -
Trim spacesKQL
SecurityEvent | extend Clean = trim(@"\s+", Computer) -
Replace textKQL
SecurityEvent | extend Account = replace_string(Account, "CONTOSO\\", "") -
Take part of a stringKQL
SecurityEvent | extend Short = substring(Computer, 0, 10) -
Length of a stringKQL
SecurityEvent | extend Len = strlen(CommandLine) | where Len > 1000 -
Find where text starts in a stringKQL
Syslog | extend Pos = indexof(SyslogMessage, "error") -
Decode base64KQL
DeviceProcessEvents | extend Decoded = base64_decode_tostring("SGVsbG8=") -
Decode a URLKQL
CommonSecurityLog | extend Url = url_decode(RequestURL) -
Split a URL into partsKQL
CommonSecurityLog | extend Parts = parse_url(RequestURL) | extend Host = tostring(Parts.Host) -
Hash a valueKQL
SecurityEvent | extend Hash = hash_sha256(Computer) -
Pull every match out of textKQL
Syslog | extend IPs = extract_all(@"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", SyslogMessage) -
Whole word, case-sensitive (fastest)KQL
SecurityEvent | where CommandLine has_cs "Invoke-Mimikatz" -
Doesn't contain a wordKQL
SecurityEvent | where CommandLine !has "svchost" -
Ends withKQL
SecurityEvent | where Account endswith "$" -
Convert text to a numberKQL
SecurityEvent | extend Port = toint(DestinationPort) -
Convert text to a dateKQL
SecurityEvent | extend When = todatetime(EventTime) -
Round a numberKQL
Perf | extend Value = round(CounterValue, 2) -
Group numbers into rangesKQL
Perf | summarize count() by bin(CounterValue, 10)
Choosing and changing columns #
-
Keep only some columnsKQL
SigninLogs | project TimeGenerated, UserPrincipalName, IPAddress, ResultType -
Drop some columnsKQL
SecurityEvent | project-away TenantId, SourceSystem -
Rename a columnKQL
SigninLogs | project-rename User = UserPrincipalName -
Add a calculated columnKQL
SigninLogs | extend Failed = ResultType != "0" -
Pick a value with if/elseKQL
SecurityEvent | extend Result = iff(EventID == 4624, "Success", "Failure") -
Pick a value from several casesKQL
SigninLogs | extend Risk = case(RiskLevelDuringSignIn == "high", 3, RiskLevelDuringSignIn == "medium", 2, 1) -
Join text togetherKQL
SecurityEvent | extend Who = strcat(Account, " on ", Computer) -
Use the first value that isn't emptyKQL
SigninLogs | extend Name = coalesce(UserDisplayName, UserPrincipalName) -
Remove duplicate rowsKQL
SigninLogs | distinct UserPrincipalName, IPAddress
Summarising #
-
Count by a columnKQL
SecurityEvent | summarize count() by Computer -
Count and sort, biggest firstKQL
SecurityEvent | summarize Count = count() by Computer | sort by Count desc -
Top 10 by countKQL
SecurityEvent | summarize Count = count() by Computer | top 10 by Count -
Count distinct valuesKQL
SigninLogs | summarize Users = dcount(UserPrincipalName) -
Count only rows that matchKQL
SigninLogs | summarize Failures = countif(ResultType != "0"), Total = count() by UserPrincipalName -
List the distinct values per groupKQL
SigninLogs | summarize IPs = make_set(IPAddress) by UserPrincipalName -
Get the latest row for each itemKQL
Heartbeat | summarize arg_max(TimeGenerated, *) by Computer -
First and last time seenKQL
SigninLogs | summarize FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by UserPrincipalName -
Average, minimum and maximumKQL
Perf | where CounterName == "% Processor Time" | summarize avg(CounterValue), min(CounterValue), max(CounterValue) by Computer -
PercentilesKQL
Perf | where CounterName == "% Processor Time" | summarize percentiles(CounterValue, 50, 95, 99) by Computer
More operators #
-
Show any one row per groupKQL
SecurityEvent | summarize take_any(*) by Computer -
Earliest row for each itemKQL
SigninLogs | summarize arg_min(TimeGenerated, *) by UserPrincipalName -
List every value per group (with duplicates)KQL
SecurityEvent | summarize Events = make_list(EventID) by Computer -
Count matching rows only, distinctKQL
SigninLogs | summarize FailedUsers = dcountif(UserPrincipalName, ResultType != "0") by IPAddress -
Top 3 inside top 3 (nested)KQL
SecurityEvent | top-nested 3 of Computer by count(), top-nested 3 of Account by count() -
Random sample of rowsKQL
SecurityEvent | sample 10 -
Number the rowsKQL
SigninLogs | sort by TimeGenerated asc | extend Row = row_number() -
Compare with the previous rowKQL
SigninLogs | where UserPrincipalName == "[email protected]" | sort by TimeGenerated asc | extend PrevIP = prev(IPAddress) | where IPAddress != PrevIP -
Add columns from a small table (lookup)KQL
SecurityEvent | lookup kind=leftouter (IdentityInfo | project Account = AccountName, Department) on Account -
Make a small table in the queryKQL
datatable(Port:int, Service:string) [22, "SSH", 3389, "RDP", 445, "SMB"] -
Load a list from a URLKQL
externaldata(IP:string) [@"https://example.com/blocklist.txt"] with (format="txt") -
Print a value to test an expressionKQL
print now(), ago(1d), strlen("hello") -
Make a list of numbersKQL
range n from 1 to 10 step 1 -
Write a function you can callKQL
let FailedFor = (upn:string) { SigninLogs | where UserPrincipalName =~ upn and ResultType != "0" }; FailedFor("[email protected]") -
Find patterns in the data automaticallyKQL
SecurityEvent | where TimeGenerated > ago(1d) | evaluate autocluster() -
Spot anomalies in a time seriesKQL
SecurityEvent | make-series Count = count() on TimeGenerated from ago(14d) to now() step 1h | extend Anomalies = series_decompose_anomalies(Count) | render anomalychart with (anomalycolumns=Anomalies) -
Check if a list contains a valueKQL
SigninLogs | summarize Apps = make_set(AppDisplayName) by UserPrincipalName | where set_has_element(Apps, "Azure Portal") -
Keys inside a JSON objectKQL
SecurityEvent | extend Keys = bag_keys(parse_json(AdditionalData))
Charts #
-
Line chart over timeKQL
SecurityEvent | where TimeGenerated > ago(7d) | summarize count() by bin(TimeGenerated, 1h) | render timechart -
Line chart with one line per groupKQL
SecurityEvent | where TimeGenerated > ago(1d) | summarize count() by bin(TimeGenerated, 1h), EventID | render timechart -
Bar chartKQL
SecurityEvent | summarize count() by Computer | render barchart -
Pie chartKQL
SecurityEvent | summarize count() by Computer | render piechart -
Time series with gaps filled with zeroKQL
SecurityEvent | make-series Count = count() default = 0 on TimeGenerated from ago(7d) to now() step 1h | render timechart
Joins and unions #
-
Join two tables (matches only)KQL
SigninLogs | join kind=inner (AuditLogs | extend UserPrincipalName = tostring(InitiatedBy.user.userPrincipalName)) on UserPrincipalName -
Keep everything from the left tableKQL
SigninLogs | join kind=leftouter (IdentityInfo | project AccountUPN, Department) on $left.UserPrincipalName == $right.AccountUPN -
Keep rows with no match on the rightKQL
Heartbeat | distinct Computer | join kind=leftanti (SecurityEvent | distinct Computer) on Computer -
Stack tables on top of each otherKQL
union SecurityEvent, Syslog | where TimeGenerated > ago(1h) -
Stack tables and show which table each row came fromKQL
union withsource=SourceTable SigninLogs, AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(1h) -
Look up values in a watchlist (Sentinel)KQL
_GetWatchlist('HighValueAssets') -
Filter by a watchlist (Sentinel)KQL
let assets = _GetWatchlist('HighValueAssets') | project SearchKey; SecurityEvent | where Computer in (assets) -
Reuse a result inside the same queryKQL
let recent = materialize(SecurityEvent | where TimeGenerated > ago(1h)); recent | count
Parsing text and JSON #
-
Read a field inside JSONKQL
SigninLogs | extend City = tostring(LocationDetails.city) -
Turn text into JSONKQL
SecurityEvent | extend Data = parse_json(AdditionalData) -
Split one row per item in a listKQL
SigninLogs | mv-expand Policy = ConditionalAccessPolicies | extend PolicyName = tostring(Policy.displayName), PolicyResult = tostring(Policy.result) -
Pull a value out with a regular expressionKQL
Syslog | extend SrcIP = extract(@"(\d{1,3}(\.\d{1,3}){3})", 1, SyslogMessage) -
Pull values out with a patternKQL
Syslog | parse SyslogMessage with * "user " User " from " SrcIP " port " * -
Split text into partsKQL
SecurityEvent | extend Parts = split(Computer, ".") -
Make every JSON field its own columnKQL
AzureActivity | evaluate bag_unpack(Properties_d) -
Look up where an IP address isKQL
SigninLogs | extend Geo = geo_info_from_ip_address(IPAddress) | extend Country = tostring(Geo.country)
Writing fast queries #
-
Filter on time firstKQL
SecurityEvent | where TimeGenerated > ago(1h) | where Computer == "web01" -
Keep only the columns you need earlyKQL
SigninLogs | where TimeGenerated > ago(1d) | project UserPrincipalName, IPAddress, ResultType | summarize count() by UserPrincipalName -
Use has instead of contains where you canKQL
Syslog | where SyslogMessage has "failed"
Sign-in and identity hunting #
-
Failed sign-ins in the last dayKQL
SigninLogs | where TimeGenerated > ago(1d) | where ResultType != "0" | project TimeGenerated, UserPrincipalName, IPAddress, ResultType, ResultDescription -
Users with the most failed sign-insKQL
SigninLogs | where TimeGenerated > ago(1d) and ResultType != "0" | summarize Failures = count() by UserPrincipalName | top 10 by Failures -
Password spray: one IP failing against many usersKQL
SigninLogs | where TimeGenerated > ago(1d) and ResultType != "0" | summarize Users = dcount(UserPrincipalName) by IPAddress | where Users > 10 -
Sign-ins for one userKQL
SigninLogs | where UserPrincipalName =~ "[email protected]" | project TimeGenerated, IPAddress, AppDisplayName, ResultType, Location -
Everything from one IP addressKQL
search "203.0.113.50" | summarize count() by $table -
Users signing in from more than one countryKQL
SigninLogs | where TimeGenerated > ago(1d) and ResultType == "0" | summarize Countries = make_set(Location) by UserPrincipalName | where array_length(Countries) > 1 -
Risky sign-insKQL
SigninLogs | where RiskLevelDuringSignIn in ("medium", "high") | project TimeGenerated, UserPrincipalName, IPAddress, RiskLevelDuringSignIn, RiskDetail -
Sign-ins that didn't use MFAKQL
SigninLogs | where ResultType == "0" and AuthenticationRequirement == "singleFactorAuthentication" | summarize count() by UserPrincipalName, AppDisplayName -
Conditional Access failuresKQL
SigninLogs | where ConditionalAccessStatus == "failure" | project TimeGenerated, UserPrincipalName, AppDisplayName, IPAddress -
Who was added to a role in Entra IDKQL
AuditLogs | where OperationName == "Add member to role" | extend Actor = tostring(InitiatedBy.user.userPrincipalName), Target = tostring(TargetResources[0].userPrincipalName) | project TimeGenerated, Actor, Target -
New inbox rules (possible mail forwarding)KQL
OfficeActivity | where Operation in ("New-InboxRule", "Set-InboxRule") | project TimeGenerated, UserId, ClientIP, Parameters
Sentinel alerts, incidents and threat intel #
-
Alerts by severity in the last weekKQL
SecurityAlert | where TimeGenerated > ago(7d) | summarize count() by AlertSeverity, ProviderName -
Latest state of each incidentKQL
SecurityIncident | summarize arg_max(TimeGenerated, *) by IncidentNumber | project IncidentNumber, Title, Severity, Status, Owner -
Open high-severity incidentsKQL
SecurityIncident | summarize arg_max(TimeGenerated, *) by IncidentNumber | where Status != "Closed" and Severity == "High" -
Match sign-in IPs against threat intelKQL
let iocs = ThreatIntelligenceIndicator | where Active == true and isnotempty(NetworkIP) | distinct NetworkIP; SigninLogs | where IPAddress in (iocs) -
Users with the highest UEBA priorityKQL
BehaviorAnalytics | where TimeGenerated > ago(1d) | summarize Priority = max(InvestigationPriority) by UserPrincipalName | top 10 by Priority -
Non-interactive sign-ins (service and token use)KQL
AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(1d) and ResultType != "0" | summarize count() by UserPrincipalName, AppDisplayName -
DNS lookups for a domainKQL
DnsEvents | where Name has "contoso.com" | project TimeGenerated, ClientIP, Name, IPAddresses -
Sign-ins from any source using ASIMKQL
_Im_Authentication(starttime=ago(1d), eventresult='Failure') | summarize count() by TargetUsername, SrcIpAddr
Windows and endpoint hunting #
-
Failed Windows logons by accountKQL
SecurityEvent | where EventID == 4625 | summarize Failures = count() by TargetAccount, IpAddress, Computer | where Failures > 10 -
Account lockoutsKQL
SecurityEvent | where EventID == 4740 | project TimeGenerated, TargetAccount, Computer -
Users added to local or domain admin groupsKQL
SecurityEvent | where EventID in (4728, 4732, 4756) | project TimeGenerated, Computer, Account, MemberName, TargetAccount -
Security log clearedKQL
SecurityEvent | where EventID == 1102 | project TimeGenerated, Computer, Account -
New services installedKQL
SecurityEvent | where EventID == 4697 | project TimeGenerated, Computer, Account, ServiceName, ServiceFileName -
Encoded PowerShell commands (Defender)KQL
DeviceProcessEvents | where FileName in~ ("powershell.exe", "pwsh.exe") | where ProcessCommandLine has_any ("-enc", "-EncodedCommand") | project Timestamp, DeviceName, AccountName, ProcessCommandLine -
Processes started on a device (Defender)KQL
DeviceProcessEvents | where DeviceName startswith "web01" | project Timestamp, AccountName, FileName, ProcessCommandLine, InitiatingProcessFileName -
Rare processes across all devices (Defender)KQL
DeviceProcessEvents | where Timestamp > ago(7d) | summarize Devices = dcount(DeviceName) by FileName | where Devices < 3 -
RDP connections out of devices (Defender)KQL
DeviceNetworkEvents | where RemotePort == 3389 and ActionType == "ConnectionSuccess" | project Timestamp, DeviceName, RemoteIP, InitiatingProcessFileName -
Connections to a domain (Defender)KQL
DeviceNetworkEvents | where RemoteUrl has "contoso.com" | project Timestamp, DeviceName, RemoteUrl, RemoteIP -
Phishing emails delivered (Defender)KQL
EmailEvents | where ThreatTypes has "Phish" and DeliveryAction == "Delivered" | project Timestamp, RecipientEmailAddress, SenderFromAddress, Subject -
Processes started, with command lines (event 4688)KQL
SecurityEvent | where EventID == 4688 | project TimeGenerated, Computer, Account, NewProcessName, CommandLine -
New user accounts createdKQL
SecurityEvent | where EventID == 4720 | project TimeGenerated, Computer, Account, TargetAccount -
Passwords reset by someone elseKQL
SecurityEvent | where EventID == 4724 | project TimeGenerated, Account, TargetAccount -
Logons with explicit credentials (runas)KQL
SecurityEvent | where EventID == 4648 | project TimeGenerated, Computer, Account, TargetServerName -
Services installed, from the System logKQL
Event | where Source == "Service Control Manager" and EventID == 7045 | project TimeGenerated, Computer, RenderedDescription -
Files dropped in Downloads (Defender)KQL
DeviceFileEvents | where ActionType == "FileCreated" and FolderPath has "\\Downloads\\" | project Timestamp, DeviceName, FileName, InitiatingProcessFileName -
Run keys added for persistence (Defender)KQL
DeviceRegistryEvents | where ActionType == "RegistryValueSet" and RegistryKey has @"\CurrentVersion\Run" | project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData -
Remote desktop logons to devices (Defender)KQL
DeviceLogonEvents | where LogonType == "RemoteInteractive" and ActionType == "LogonSuccess" | project Timestamp, DeviceName, AccountName, RemoteIP -
Failed logons against domain controllers (Defender for Identity)KQL
IdentityLogonEvents | where ActionType == "LogonFailed" | summarize Failures = count() by AccountUpn, IPAddress | where Failures > 10 -
Alerts with the devices involved (Defender)KQL
AlertInfo | join kind=inner (AlertEvidence | where isnotempty(DeviceName)) on AlertId | project Timestamp, Title, Severity, DeviceName -
Devices with a vulnerability (Defender)KQL
DeviceTvmSoftwareVulnerabilities | where CveId == "CVE-2024-3400" | project DeviceName, SoftwareName, SoftwareVersion -
Devices by operating system (Defender)KQL
DeviceInfo | summarize arg_max(Timestamp, *) by DeviceId | summarize count() by OSPlatform, OSVersion -
Cloud app activity by a user (Defender for Cloud Apps)KQL
CloudAppEvents | where AccountDisplayName has "jsmith" | project Timestamp, Application, ActionType, IPAddress
Azure and workspace health #
-
Resources deleted in AzureKQL
AzureActivity | where OperationNameValue endswith "DELETE" and ActivityStatusValue == "Success" | project TimeGenerated, Caller, OperationNameValue, ResourceGroup, _ResourceId -
Machines that stopped sending heartbeatsKQL
Heartbeat | summarize LastSeen = max(TimeGenerated) by Computer | where LastSeen < ago(1h) -
Billable data per table in the last 30 days (GB)KQL
Usage | where TimeGenerated > ago(30d) and IsBillable | summarize GB = sum(Quantity) / 1000 by DataType | sort by GB desc -
Firewall and proxy logs blocked from one sourceKQL
CommonSecurityLog | where SourceIP == "203.0.113.50" and DeviceAction in~ ("deny", "drop", "block") | summarize count() by DestinationIP, DestinationPort -
Linux sudo use from SyslogKQL
Syslog | where ProcessName == "sudo" | project TimeGenerated, Computer, SyslogMessage -
Role assignments made in AzureKQL
AzureActivity | where OperationNameValue =~ "MICROSOFT.AUTHORIZATION/ROLEASSIGNMENTS/WRITE" and ActivityStatusValue == "Success" | project TimeGenerated, Caller, ResourceGroup -
Key Vault secrets readKQL
AzureDiagnostics | where ResourceProvider == "MICROSOFT.KEYVAULT" and OperationName == "SecretGet" | project TimeGenerated, Resource, CallerIPAddress, identity_claim_upn_s -
Who changed network security groupsKQL
AzureActivity | where OperationNameValue has "MICROSOFT.NETWORK/NETWORKSECURITYGROUPS" and ActivityStatusValue == "Success" | project TimeGenerated, Caller, OperationNameValue, ResourceGroup -
Busiest machines by CPUKQL
Perf | where CounterName == "% Processor Time" and TimeGenerated > ago(1h) | summarize AvgCPU = avg(CounterValue) by Computer | top 10 by AvgCPU