4104 at Scale: Turning PowerShell Script Block Logging Into Telemetry Your SOC Will Actually Keep
Photo: Daderot, CC0, via Wikimedia Commons
Enabling PowerShell script block logging takes about ninety seconds. Getting value out of the resulting events is a project. Most Windows fleets in 2026 have the checkbox ticked — it's a common audit finding, and Microsoft's own baselines push it — yet the events sit in a rolling operational log that nobody queries until an incident review, at which point half the evidence has already overwritten itself.
That's the gap worth closing. Logging is solved. Visibility isn't.
What 4104 actually contains
The event lands in Microsoft-Windows-PowerShell/Operational. Enable it via Group Policy (Administrative Templates → Windows Components → Windows PowerShell → Turn on PowerShell Script Block Logging) or the registry value HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging\EnableScriptBlockLogging = 1.
Each 4104 record carries the deobfuscated script block text — the engine logs what it's about to compile, not the raw command line, which is why base64-encoded launchers show up in plaintext. It also carries two fields that decide your architecture:
ScriptBlockId— a GUID identifying the whole block.MessageNumberandMessageTotal— large blocks are split across multiple events.
If your parser stores each event as an independent row, every script over roughly 20 KB becomes a shredded document. Reassemble by grouping on ScriptBlockId and ordering by MessageNumber, or you'll be reading half a download cradle and drawing the wrong conclusion.
Do not casually flip on EnableScriptBlockInvocationLogging. That produces 4105/4106 start-and-stop pairs for every call and can multiply volume by an order of magnitude. Turn it on for a scoped pilot, never fleet-wide by default.
Noise tuning before alerting
The first week of 4104 data is humbling — mostly because 80% of it is legitimate tooling. Expect to see: Intune and ConfigMgr management scripts, endpoint protection agent wrappers, software deployment frameworks, printer driver helpers, and your own module imports. On servers, add scheduled maintenance scripts and monitoring probes.
Tune in three layers, cheapest first:
- Filter at the source. WEF subscriptions or your agent config can exclude known-good script block hashes. Maintain an allow-list keyed on
ScriptBlockIdplus a content hash — not on path, which attackers and packagers both change freely. - Filter known-benign patterns at query time. Vendor bootstrappers typically have distinctive first lines.
- Never filter by username alone. Service accounts run plenty of legitimate PowerShell and eventually run something else too.
Keep a written record of every exclusion with an owner and a review date. The most common failure mode isn't a missed detection — it's an exclusion added during an outage in 2024 that nobody remembers and nobody revisits.
Enrichment: three streams, one story
4104 in isolation answers "what code ran." Pair it with two neighbors and it starts answering "who, from where, and did anything else notice."
- Transcription (
HKLM\SOFTWARE\Policies\Microsoft\PowerShell\Transcription,EnableTranscripting = 1, withOutputDirectoryandEnableInvocationHeader) captures command input and output, tied to a user and host. That fills in the results 4104 never shows. Point output at a protected share with strict ACLs — transcripts contain secrets more often than anyone expects. - Module logging (4103) records pipeline execution detail and parameter binding. High volume, so scope it to security-sensitive modules rather than the whole box.
- AMSI and Defender telemetry (
Microsoft-Windows-Windows Defender/Operational, plus your AMSI provider) gives you the verdicts: what content was flagged, quarantined, or blocked. Joining a 4104 block to a Defender detection on the same host within minutes is one of the highest-signal correlations you can build.
Add host context — asset criticality, owning team, exposure — at ingest, not at query time. An analyst at 3 A.M. should not need to look up whether WEB-PRD-07 is internet-facing.
Getting it off the box
A local operational log with a 1 GB cap and default retention is not evidence. Pick a forwarding path and standardize:
- Windows Event Forwarding for domain-joined fleets — cheap, built-in, and the collector can do filtering before events hit the network.
- Azure Monitor Agent with a data collection rule for cloud-connected and hybrid hosts, feeding Log Analytics or Sentinel.
- Your existing SIEM agent if one is already deployed and healthy. Don't add a second agent for one channel.
Whatever you choose, verify with a spot check monthly. Forwarding silently breaks — a certificate expires, a DCR gets detached, an agent goes unhealthy — and nobody notices until the incident.
Queries that survive contact with reality
In Log Analytics / Sentinel, a starting point for reassembled blocks:
Event
| where Source == 'Microsoft-Windows-PowerShell' and EventID == 4104
| extend Xml = parse_xml(EventData)
| extend ScriptBlockId = tostring(Xml.EventData.Data[2]['#text']),
BlockText = tostring(Xml.EventData.Data[1]['#text'])
| where BlockText has_any ('DownloadString', 'FromBase64String', 'Invoke-Expression', 'Net.WebClient')
| project TimeGenerated, Computer, ScriptBlockId, BlockText
| take 100
Field indices vary by collector and Windows build — validate against your own data before shipping a detection. If you're querying locally, keep it simple:
Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-PowerShell/Operational'
Id = 4104
StartTime = (Get-Date).AddHours(-4)
} | Select-Object TimeCreated, @{n='Block';e={$_.Properties[2].Value}}
Detection content worth maintaining tends to share traits: it keys on behaviors, not strings. Flag IEX + DownloadString in the same block. Flag Set-MpPreference with -DisableScriptScanning or exclusion arguments. Flag [AMSI](https://en.wikipedia.org/wiki/ClamAV) string manipulation and amsiutils references. Flag blocks whose text matches known payload shapes rather than one specific hashtag. Then version the rule, attribute it to an owner, and give it a test corpus — a rule you can't regression-test is a rule you'll quietly disable.
The PowerShell 7 blind spot
Plenty of fleets still only collect Microsoft-Windows-PowerShell/Operational. PowerShell 7 writes its script block events to a separate channel — PowerShellCore/Operational — and reads its policy from a separate branch. If your queries, WEF subscription, or DCR hardcodes the Windows PowerShell provider name, every pwsh process on the estate is invisible. Since PowerShell 7 is now the default on modern Windows Server images and everywhere in CI images, that's not an edge case; it's a hole. Update collectors, then confirm with a pwsh -c 'Get-Date' test on a canary host.
Rollout checklist
- Enable script block logging by GPO across a pilot OU; verify 4104 arrives within the hour.
- Enable transcription on servers handling privileged operations; lock down the output share.
- Confirm PowerShell 7 coverage on both Windows PowerShell and PowerShellCore channels.
- Stand up forwarding and validate end-to-end with a known test string.
- Build the allow-list from two weeks of real data, with owners and review dates.
- Ship three behavioral detections with test cases before shipping thirty untested ones.
- Set retention deliberately — 90 days hot is a reasonable floor for most regulated US environments.
- Schedule a monthly forwarding health check and a quarterly exclusion review.
Script block logging is the easy half. The half that matters is the pipeline behind it — filtered, reassembled, enriched, forwarded, and owned by someone whose name is written down.