KQL cheat sheet for Microsoft Defender and Sentinel threat hunting

Latest Comments

No comments to show.
Abstract security operations dashboard with query lines and log analytics, representing KQL threat hunting in Microsoft Defender and Sentinel

If you are already using Microsoft Defender and Microsoft Sentinel, KQL is the common language that lets you move from raw telemetry to useful hunting hypotheses. The challenge is rarely syntax alone. It is knowing which tables to start with, how to shape the data quickly, and how to turn a one-off search into something repeatable and operationally useful.

This cheat sheet is written for technical practitioners who want a practical reference rather than a theory piece. It focuses on the query patterns that tend to matter most in day-to-day hunting: process execution, identity activity, persistence, lateral movement, and the small set of operators that make KQL productive. If you want a broader hunting methodology, it is worth pairing this with our Microsoft Sentinel hunting guide and the article on building analytics rules from MITRE ATT&CK techniques.

Key takeaways

  • Start with a small set of high-value tables and query patterns rather than trying to hunt everything at once.
  • Use KQL hunts to explore behaviour first, then simplify and tune the best patterns before turning them into analytics rules.
  • Correlate endpoint, identity and network telemetry to raise confidence and reduce false positives.
  • Test queries against known-good activity and maintain allow lists carefully so you do not suppress useful signals.

What this cheat sheet is for

KQL is useful in two different modes. In hunting mode, you are exploring a question such as “what unusual PowerShell ran in the last 24 hours?” or “which accounts suddenly started failing authentication from multiple countries?” In alerting mode, you are codifying a pattern into a rule that should fire consistently and with acceptable noise.

That distinction matters because the same query often needs different treatment depending on the goal. A hunting query can be broader, more exploratory, and more expensive. An analytics rule should be narrower, deterministic, and tuned for repeatability. If you try to use a raw hunt as an alert, you usually get false positives. If you make an alert too narrow too early, you miss the behaviour you were trying to detect.

For UK SMEs, the practical aim is not to hunt everything. It is to build a small set of reusable searches that cover the highest-value behaviours: suspicious execution, identity abuse, persistence, and lateral movement. That gives you a defensible baseline without needing a large SOC.

When to use KQL for hunting versus alerting

Use KQL for hunting when you want to answer an open question, validate a hypothesis, or understand whether a signal is worth operationalising. Use it for alerting when the behaviour is specific enough that you can describe it in a stable way, and when the cost of missing it is higher than the cost of investigating a small number of false positives.

A useful rule of thumb is this: if you cannot explain the expected result set in one sentence, the query is probably still a hunt, not an alert.

How to adapt the examples for your own tenant

Most examples below use common Microsoft Defender for Endpoint and Sentinel tables, but your tenant may ingest different sources or use different retention settings. Start by checking the schema in your workspace, then replace table names and field names where needed. In practice, the most common adjustments are device identifiers, account fields, and timestamp columns.

Also be careful with time windows. A query that works well over 24 hours may be too noisy over seven days, and a query that is useful for hunting may be too slow for a scheduled rule. If you are dealing with ingestion delay, remember that Sentinel query windows need to be wide enough to account for late-arriving data, as discussed in our article on log ingestion delay and detection latency.

KQL essentials for Defender and Sentinel

KQL is readable once you get used to the pipeline model. Each stage takes a table, transforms it, and passes the result to the next stage. Most hunting queries are just a few building blocks chained together: filter, shape, aggregate, and correlate.

Core query structure: tables, filters, projections and summarisation

A basic pattern looks like this:

TableName
| where Timestamp between (ago(24h) .. now())
| where ActionType == "SomeAction"
| project Timestamp, DeviceName, AccountName, FileName
| summarize count() by DeviceName, AccountName

The important parts are straightforward. The table defines the data source. where filters rows. project selects the columns you want to see. summarize groups and counts, or otherwise aggregates the data.

For hunting, keep your first pass simple. Add complexity only when the result set is too broad or too narrow. A common mistake is to start with joins and parsing before checking whether the basic filter is even returning the right events.

Time filtering, joins and unions

Time filtering is usually the first thing to get right. In Sentinel and Defender, most tables include a timestamp column, but the exact name varies. Use ago() for relative windows and between for explicit ranges. For example, a 24-hour hunt often starts with where Timestamp > ago(24h).

joins are for correlation. Use them when you want to connect activity across tables, such as a suspicious process followed by a network connection, or a sign-in followed by a risky audit event. unions are for combining similar event streams, especially when the same behaviour can appear in more than one table.

Be cautious with joins on high-volume tables. If you join too early, you can create expensive queries and duplicate rows. Filter first, then join on the smallest useful dataset.

Useful operators: where, project, extend, summarize, parse and mv-expand

where is your main filter. project trims the output. extend creates derived fields, which is useful for normalising or extracting values. summarize aggregates. parse is helpful when a field contains semi-structured text. mv-expand is useful when a field contains arrays or dynamic values that need to be broken out into rows.

In practice, extend and parse are often what turn a noisy hunt into something readable. For example, you might extract a command-line switch, normalise a hostname, or derive a simple risk flag from several conditions.

High-value tables to know first

You do not need to memorise every table in Microsoft Defender or Sentinel. Start with the ones that give you the best coverage for endpoint, identity, and cloud activity. If you are building a small but effective hunting capability, these are usually the first places to look.

Microsoft Defender for Endpoint tables

Commonly useful tables include DeviceProcessEvents, DeviceNetworkEvents, DeviceFileEvents, DeviceRegistryEvents, DeviceLogonEvents, and DeviceEvents. These give you process execution, network activity, file changes, registry changes, logons, and general device telemetry.

DeviceProcessEvents is often the most valuable starting point for endpoint hunting because it gives you parent-child process relationships, command lines, hashes, and account context. DeviceNetworkEvents is useful when you want to see whether a process talked to an unusual destination. DeviceRegistryEvents and DeviceFileEvents are useful for persistence and tampering.

Microsoft Sentinel and Microsoft 365 Defender tables

In Sentinel, you will often work with tables such as SecurityEvent, SigninLogs, AuditLogs, OfficeActivity, CommonSecurityLog, and AzureActivity, depending on what you ingest. Microsoft 365 Defender data may also be available through advanced hunting tables or connected data sources.

If you are hunting identity abuse, SigninLogs and AuditLogs are usually the first place to start. If you are looking for cloud control-plane activity, AzureActivity is useful. If you need email or collaboration telemetry, OfficeActivity can be valuable, although the exact fields and retention depend on your licensing and connector configuration.

Identity, device and audit data sources

Good hunts usually combine identity and endpoint context. A suspicious process on a device is more meaningful if the account is privileged, recently created, or associated with unusual sign-in behaviour. Likewise, a risky sign-in becomes more actionable when you can tie it to a device or subsequent mailbox or directory activity.

That is why centralised visibility matters. If you are still building out your logging strategy, our article on achieving centralised visibility across endpoints, identity and network is a useful companion piece.

Common hunting patterns and reusable query building blocks

Most useful hunts fall into a few repeatable patterns. Once you recognise them, you can adapt the same structure across different tables and behaviours.

Finding rare or unusual activity

Rare activity is often more interesting than obviously malicious activity. A process that almost never runs in your environment, a user who rarely signs in from a given geography, or a device that suddenly starts making outbound connections to a new domain can all be worth a closer look.

DeviceProcessEvents
| where Timestamp > ago(7d)
| summarize executions = count() by FileName
| where executions < 10
| order by executions asc

This is a simple rarity check. In a real hunt, you would usually add context, such as parent process, signer, or device group, to avoid overreacting to legitimate admin tools or software deployment activity.

Looking for repeated failures, bursts and outliers

Repeated failures and bursts are useful because they often indicate automation, spraying, or abuse. The pattern is usually count events over a short window, then compare against a threshold or baseline.

SigninLogs
| where TimeGenerated > ago(1h)
| summarize failures = countif(ResultType != 0), successes = countif(ResultType == 0) by UserPrincipalName, IPAddress
| where failures > 10 and successes == 0
| order by failures desc

That query is intentionally simple. You can refine it by adding country, device, application, or conditional access outcome. The main point is to identify concentration rather than isolated noise.

Correlating activity across users, hosts and IP addresses

Correlation is where KQL becomes especially useful. A single event may be ambiguous, but a sequence of events across tables can be much more convincing. For example, a suspicious process, followed by a network connection, followed by a registry change, is more interesting than any one of those events alone.

When correlating, normalise the join keys carefully. Hostnames, device IDs, and account names are not always consistent across sources. If you need to match on multiple fields, use extend to create a common field first.

Process and command-line hunting

Process telemetry is one of the richest sources for hunting because it captures execution context. The most useful questions are usually about parent-child chains, command-line patterns, and whether a legitimate binary is being used in an unusual way.

Suspicious parent-child process chains

One of the simplest and most effective hunts is to look for unusual parent-child combinations. For example, Office spawning script hosts, browsers spawning shells, or service processes spawning interactive tools can all merit review.

DeviceProcessEvents
| where Timestamp > ago(24h)
| where InitiatingProcessFileName in~ ("winword.exe", "excel.exe", "outlook.exe", "powerpnt.exe")
| project Timestamp, DeviceName, FileName, ProcessCommandLine, InitiatingProcessFileName, AccountName
| order by Timestamp desc

This is a starting point, not a verdict. In many environments, Office add-ins, automation, or document processing tools can produce similar patterns. The value comes from reviewing the surrounding context and comparing against normal business activity.

Encoded commands, script hosts and LOLBins

Encoded commands and living-off-the-land binaries, or LOLBins, are common hunting targets because they are often used to blend in with normal administration. PowerShell, wscript, cscript, mshta, rundll32, regsvr32, and certutil are all worth watching in the right context.

DeviceProcessEvents
| where Timestamp > ago(24h)
| where ProcessCommandLine has_any ("-enc", "-encodedcommand", "FromBase64String", "IEX", "Invoke-Expression")
| project Timestamp, DeviceName, FileName, ProcessCommandLine, InitiatingProcessFileName, AccountName
| order by Timestamp desc

For PowerShell-specific review, script block logging and command-line telemetry are complementary. If you want a deeper treatment of this area, our article on anomalous PowerShell with script block logging goes into more detail.

PowerShell, WMI and scheduled task activity

PowerShell, WMI, and scheduled tasks are common for both legitimate administration and persistence. The trick is to look for combinations that are unusual in your environment, such as a new task created by a low-privilege account or a script host launched from a user-writable directory.

For scheduled tasks specifically, it is often useful to combine process creation with task creation events and registry changes. That gives you a better view of whether the task was created, modified, or used for persistence.

Identity and sign-in hunting

Identity telemetry is often the fastest way to spot abuse in Microsoft environments. The most useful hunts focus on sign-in anomalies, password spraying, privilege use, and suspicious consent or audit activity.

Risky sign-ins and impossible travel style patterns

Risky sign-ins are usually best treated as a triage queue rather than a final answer. Look for repeated failures, unfamiliar locations, new devices, and sign-ins that do not fit the user’s normal pattern.

SigninLogs
| where TimeGenerated > ago(24h)
| summarize countries = make_set(LocationDetails.countryOrRegion), ipCount = dcount(IPAddress), apps = make_set(AppDisplayName) by UserPrincipalName
| where ipCount > 3
| order by ipCount desc

This does not prove compromise. It highlights accounts that deserve closer inspection. If you are already hunting risky sign-ins, you may also find our article on risky Entra ID sign-ins in Sentinel useful as a companion reference.

Password spraying and brute-force indicators

Password spraying often shows up as many users targeted from the same IP or source range, usually with one or two attempts per account. Brute-force activity is more likely to show repeated failures against a single account. Both can be approximated with KQL by grouping on IP address, user, and time window.

SigninLogs
| where TimeGenerated > ago(2h)
| where ResultType != 0
| summarize failedUsers = dcount(UserPrincipalName), failures = count() by IPAddress
| where failedUsers > 5 and failures > 20
| order by failures desc

Thresholds should reflect your environment. A remote workforce, shared VPN egress, or third-party integrations can all change what “normal” looks like.

Privilege use, consent events and anomalous authentication

Privilege use is worth hunting because it often marks a step change in attacker capability. Look for unusual admin role activation, new privileged group membership, and consent-related activity that does not fit normal change windows.

For cloud identity and consent telemetry, AuditLogs is often the right place to start. If you are looking specifically at OAuth consent abuse, our article on OAuth consent phishing in Microsoft 365 audit logs is a useful reference.

Endpoint and persistence hunting

Persistence often leaves small but durable traces. Registry run keys, services, startup folders, scheduled tasks, and new local administrators are all worth checking, especially when they appear shortly after an initial access event.

Run keys, services, startup items and scheduled tasks

Registry and task-based persistence can be hunted by looking for changes in known persistence locations. The exact query depends on your telemetry source, but the pattern is usually the same: filter for relevant paths, then review the process and account context.

For scheduled task hunting, a focused approach is usually better than a broad one. If you want a dedicated example set, see our article on scheduled task persistence using KQL in Sentinel.

New local administrators and group membership changes

Changes to local admin membership are high-value because they often enable follow-on actions. In Windows environments, look for group membership changes, new service accounts, and unexpected use of privileged groups outside change windows.

SecurityEvent
| where TimeGenerated > ago(24h)
| where EventID in (4728, 4732, 4756)
| project TimeGenerated, Computer, Account, TargetAccount, Activity

The event IDs you use will depend on your logging configuration and whether you are collecting domain controller, endpoint, or cloud audit data. The important part is to keep the hunt tied to a specific privilege change rather than searching for generic admin activity.

Defender for Endpoint telemetry for suspicious execution

Defender for Endpoint is especially useful when you need process, file, registry, and network context in one place. It is often the fastest route from a suspicious alert to a useful investigation trail.

For example, if you see a suspicious binary on a device, check the parent process, command line, signer, hash, and any immediate network activity. That combination is usually more informative than the filename alone.

Network and lateral movement hunting

Network telemetry helps you see what happened after execution. It is particularly useful for spotting beacon-like behaviour, unusual remote administration, and movement between hosts.

Unusual outbound connections and beacon-like behaviour

Beaconing is often characterised by repeated connections at regular intervals to the same destination. In KQL, you can approximate this by grouping on destination and counting events over a short window.

DeviceNetworkEvents
| where Timestamp > ago(1h)
| summarize connections = count(), devices = dcount(DeviceName) by RemoteUrl, RemoteIP
| where connections > 50 and devices == 1
| order by connections desc

This is not a full beacon detector, but it is a useful starting point. You can improve it by adding time-bucketing, process context, and allow lists for known update services or SaaS platforms.

Remote service creation and admin share access

Remote service creation, SMB admin share access, and remote execution tools are common lateral movement indicators. In practice, you want to correlate network activity with process creation and authentication events so that you can distinguish legitimate admin work from suspicious movement.

Where possible, look for the same account interacting with multiple hosts in a short period, especially if the account is not normally used for administration.

Correlating endpoint and network signals

Correlation across endpoint and network tables is one of the most effective ways to increase confidence. A process that launches, opens a network connection, and then writes to a persistence location is a stronger signal than any one of those actions alone.

Use join when you need to connect events by device or account, and use time windows carefully so that you do not miss the sequence. If you need a broader view of how endpoint, identity and network telemetry fit together, our article on unified threat detection across endpoint, identity and network is a useful companion.

Practical KQL functions and operators for hunters

There are a handful of functions and operators that do most of the work in hunting. If you are comfortable with these, you can build and tune queries much faster.

project, extend and parse for shaping results

Use project to keep output readable. Use extend to create helper fields, such as a lowercased username or a derived severity flag. Use parse when a field contains structured text that is easier to extract than to inspect manually.

A good habit is to project only the columns you need for triage. Too many columns make results harder to scan and can hide the important fields.

summarize, make_set and countif for aggregation

summarize is the workhorse of hunting. countif lets you count specific conditions. make_set is useful when you want to see the variety of values associated with a user, host, or IP. dcount is useful when you care about uniqueness rather than volume.

These functions are especially useful for spotting concentration, spread, and change over time. For example, a user with many failures from many IPs is different from a user with many failures from one IP.

join, union and materialize for correlation

join connects datasets. union combines them. materialize can help when you reuse the same intermediate result more than once, although you should use it carefully and only when it improves readability or performance.

In general, keep correlation steps as small as possible. Filter first, aggregate where you can, and only then join to a second dataset. That approach usually performs better and is easier to reason about during an investigation.

How to tune queries for signal quality

Good hunting is not just about finding more events. It is about finding the right events with enough confidence to act on them. That means tuning for both false positives and blind spots.

Reducing false positives without losing coverage

Start by identifying the obvious benign sources of noise: software deployment tools, admin scripts, backup systems, vulnerability scanners, and known service accounts. Then decide whether to exclude them, tag them, or handle them separately.

Do not remove a noisy source too quickly. Sometimes the noise is telling you that a control is working, or that a process is more common than you expected. A better approach is often to baseline first, then decide whether to suppress, threshold, or investigate.

Using allow lists and baselines carefully

Allow lists are useful, but they can become brittle if they are too broad or too static. Prefer scoped allow lists based on known service accounts, device groups, or signed binaries rather than blanket exclusions.

Baselines should be reviewed periodically. A query that was high-signal six months ago may now be normal because your environment changed. That is especially true in smaller organisations where tooling and admin practices evolve quickly.

Testing queries against known-good activity

Before promoting a hunt into a rule, test it against known-good examples. Use recent admin activity, deployment windows, and maintenance events to check whether the query behaves as expected. If you can, validate against a small set of known-bad samples from a controlled test environment.

This is where purple-team style validation helps. If you want a structured approach, our article on purple teaming with Atomic Red Team and MITRE ATT&CK is a good reference point for safe validation.

Sentinel-specific tips for operational use

Sentinel is not just a query surface. It is also where hunting output can become operational detection, case management, and response workflow. A good hunt should be designed with that transition in mind.

Turning a hunt into an analytics rule

If a hunt consistently produces useful results, consider turning it into an analytics rule. Before you do, check whether the query is stable, whether the data arrives in time, and whether the expected false positive rate is acceptable.

Rule logic should usually be simpler than hunt logic. Remove exploratory branches, keep the time window explicit, and make sure the entity mapping is clean enough for investigation workflows.

Working with time windows and lookback periods

Sentinel rules often need a lookback period that is longer than the scheduled run interval. That helps catch late-arriving events and ensures correlation windows are wide enough to capture related activity. The trade-off is that wider windows can increase cost and duplicate alerts if the rule is not tuned carefully.

When you move from hunt to rule, test the same logic over different time windows. A query that is fine over 24 hours may become noisy over seven days, especially if it relies on counts or rarity.

Using watchlists and entity mapping

Watchlists are useful for maintaining allow lists, critical assets, privileged accounts, or known service identities without hard-coding them into every query. Entity mapping is equally important because it improves triage and makes alerts easier to investigate.

Use both sparingly and deliberately. The goal is to reduce friction for analysts, not to hide complexity in a way that makes the rule harder to maintain.

Defender-specific tips for operational use

Microsoft Defender advanced hunting is often the fastest place to iterate on endpoint queries. It is especially useful when you need to pivot between process, file, registry, and network telemetry on the same device.

Using Advanced Hunting effectively

Start with a narrow hypothesis and expand only if the results are too sparse. Advanced hunting is powerful, but it is easy to over-query and end up with a large result set that is hard to interpret. Keep the output focused on the fields that matter for triage.

If you are investigating a single device, filter by DeviceName or DeviceId early. If you are investigating a user, include account context and then pivot to the device. That keeps the query efficient and the results manageable.

Filtering by device, user and process context

Context is what turns telemetry into evidence. A suspicious process is more meaningful if it ran under a standard user account, from a user profile path, and shortly before a network connection to an unusual destination. The same process may be far less interesting if it was launched by a known admin tool on a management server.

Always ask whether the event fits the role of the device. A jump host, a file server, and a user laptop should not generate the same expectations.

Validating results before escalation

Before escalating a hunt result, check whether there is a benign explanation. Look for software deployment, patching, backup activity, or scheduled maintenance. If the event still looks unusual after that review, capture the surrounding context so that the next analyst does not have to rediscover it.

That habit improves both investigation quality and future tuning. It also makes it easier to turn a hunt into a durable detection later on.

KQL cheat sheet examples by use case

The examples below are intentionally compact. They are designed to be adapted, not copied blindly. Replace table names, fields, and thresholds to fit your environment.

1. Suspicious PowerShell with encoded content

DeviceProcessEvents
| where Timestamp > ago(24h)
| where ProcessCommandLine has_any ("-enc", "-encodedcommand", "FromBase64String")
| project Timestamp, DeviceName, FileName, ProcessCommandLine, InitiatingProcessFileName, AccountName
| order by Timestamp desc

2. Office spawning script hosts

DeviceProcessEvents
| where Timestamp > ago(24h)
| where InitiatingProcessFileName in~ ("winword.exe", "excel.exe", "outlook.exe", "powerpnt.exe")
| where FileName in~ ("powershell.exe", "wscript.exe", "cscript.exe", "mshta.exe")
| project Timestamp, DeviceName, FileName, ProcessCommandLine, InitiatingProcessFileName, AccountName

3. Multiple failed sign-ins from one IP

SigninLogs
| where TimeGenerated > ago(2h)
| where ResultType != 0
| summarize failures = count(), users = dcount(UserPrincipalName) by IPAddress
| where failures > 20 and users > 5
| order by failures desc

4. New privileged group membership changes

SecurityEvent
| where TimeGenerated > ago(24h)
| where EventID in (4728, 4732, 4756)
| project TimeGenerated, Computer, Account, TargetAccount, Activity

5. Rare process names in the last week

DeviceProcessEvents
| where Timestamp > ago(7d)
| summarize executions = count() by FileName
| where executions < 10
| order by executions asc

6. Unusual outbound connections from one device

DeviceNetworkEvents
| where Timestamp > ago(24h)
| summarize connections = count(), destinations = dcount(RemoteIP) by DeviceName
| where connections > 200 and destinations > 20
| order by connections desc

To make these more useful, add allow lists, device role filters, and account context. For example, exclude known management servers, backup jobs, and software deployment windows. That is usually enough to turn a rough hunt into a practical operational query.

How to modify the examples for your environment

Start by identifying the tables you actually ingest, then map the fields you rely on most. If your tenant uses different connectors or retention settings, you may need to swap in equivalent tables or fields. The logic should remain the same even if the schema changes.

Next, test each query against a known-good period. If the result set is empty, the issue may be the table, the field name, or the time window. If the result set is too large, tighten the filters before adding more joins or parsing.

Finally, keep a small library of queries that you trust. A good cheat sheet is not a static document. It is a working set of patterns that your team can reuse, tune, and promote into detections when they prove their value.

If you want help turning these patterns into a more structured detection and monitoring approach, or you need support aligning Sentinel and Defender telemetry with your wider security operating model, speak to a consultant.

Frequently asked questions

What is the difference between KQL in Sentinel and Defender?

The language is the same, but the data model and operational context differ. In Microsoft Sentinel you usually query across multiple connected sources and use KQL for hunting, correlation and analytics rules. In Microsoft Defender advanced hunting you are typically working with endpoint-centric telemetry and using KQL to investigate device, process, file and network activity more directly.

How do I make KQL queries faster and more useful for hunting?

Filter early, keep the time window as small as practical, and project only the fields you need. Use summarize before joins where possible, normalise keys before correlating tables, and test the query against known-good activity so you can tune thresholds and allow lists without losing coverage.

Tags:

Comments are closed