Detect encoded PowerShell commands (KQL)
Attackers routinely launch PowerShell with -EncodedCommand (or the -enc shorthand) to hide the real script behind a Base64 blob and evade command-line inspection. This DeviceProcessEvents query matches PowerShell processes whose command line uses the encoded-command flag followed by a long Base64 string, or that pipe Base64 through FromBase64String.
The decoded payload itself is not in the log, but the encoded-execution pattern is a strong, high-volume hunting lead you can then triage per host.
The query
DeviceProcessEvents
| where Timestamp > ago(7d)
| where FileName in~ ("powershell.exe", "pwsh.exe", "powershell_ise.exe")
| where ProcessCommandLine has_any ("-enc", "-ec ", "-EncodedCommand", "FromBase64String")
| where ProcessCommandLine matches regex @"(?i)\s-e(nc(odedcommand)?)?\s+[A-Za-z0-9+/=]{20,}"
or ProcessCommandLine has "FromBase64String"
| project Timestamp, DeviceName, AccountName,
InitiatingProcessFileName, InitiatingProcessCommandLine, ProcessCommandLine
| sort by Timestamp descLine-by-line explanation
| where FileName in~ ("powershell.exe", "pwsh.exe", "powershell_ise.exe")Scopes to the PowerShell interpreters, including PowerShell 7 (pwsh.exe) and the ISE. in~ is a case-insensitive set match.
| where ProcessCommandLine has_any ("-enc", "-ec ", "-EncodedCommand", ...)A cheap pre-filter on the encoded-command flags and the common Base64 decode call before the more expensive regex runs.
matches regex @"(?i)\s-e(nc(odedcommand)?)?\s+[A-Za-z0-9+/=]{20,}"Confirms the flag is followed by a real Base64 blob (20+ Base64 chars), which cuts false positives from the flag appearing in unrelated text.
Required tables and columns
FileNameThe interpreter image; powershell.exe or pwsh.exe.ProcessCommandLineFull command line containing the encoded-command flag and Base64 payload.InitiatingProcessFileNameThe parent process, which helps distinguish admin tooling from suspicious launchers.
MITRE ATT&CK mapping
Tuning and false positives
- Baseline and exclude management agents (configuration tools, EDR, software deployment) that legitimately run encoded PowerShell.
- Decode and inspect the Base64 in triage; prioritise payloads that include IEX, DownloadString, or networking cmdlets.
Limitations
- The decoded script is not available in DeviceProcessEvents; use Script Block Logging (via DeviceEvents PowerShell actions) to see the actual code.
- Heavily obfuscated or compressed command lines may not match the Base64 regex; treat the has_any pre-filter hits as leads too.
Related queries
References
Last reviewed 2026-11-18.