Join our Newsletter — 33% off our NHI Course
Home› Guides› PowerShell Logging Detection Guide: Turning Script Block, Module…
Guide SOC & Detection Engineering

PowerShell Logging Detection Guide: Turning Script Block, Module and Transcript Logs into SOC Detections

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 19 November 2026 16 min read
On this page

PowerShell logging only helps the SOC when the right events reach the SIEM intact, are reassembled correctly and are matched against detections that reflect how attackers and automation really use the shell. This guide is for detection engineers and SOC analysts who already have PowerShell logging switched on, or are about to, and now need to turn script block, module and transcription output into reliable alerts and hunts.

Configuration and hardening of PowerShell itself, including Constrained Language mode, AMSI, removing PowerShell 2.0 and JEA, are covered in the PowerShell Security Guide. This page picks up where that one stops: what each log source records, where it lands, how to collect it, how to read it, and what to detect. It follows the same pattern as the other pages in our log source detection series, such as the Okta System Log Detection Guide.

Every event ID, log name and policy path below is taken from Microsoft's own PowerShell documentation as of November 2026. Queries are illustrative: test them against your own data and field mappings before you put them into production.

Key takeaways

  • Script block logging (event 4104 in the Microsoft-Windows-PowerShell/Operational log) is the single most valuable PowerShell source for detection, because it records the script text PowerShell actually runs.
  • PowerShell 7 writes to a separate log, PowerShellCore/Operational, with its own Group Policy node. If you only collect the Windows PowerShell channels, PowerShell 7 activity is invisible.
  • Long scripts are split across several 4104 events. Detections that inspect a single event miss content that spans fragments, so reassemble by script block ID before matching.
  • PowerShell automatically logs script blocks that contain content often used by malicious scripts, even where full logging is not configured. Treat those events as high-signal.
  • The classic Windows PowerShell log is not designed to be secure. Microsoft warns that users can read and write it, so do not rely on it alone for security auditing.
  • Service accounts, scheduled tasks and automation pipelines run a large share of PowerShell. Baseline them as non-human identities, then alert on deviation rather than on PowerShell use as such.
  • CISA's #StopRansomware Guide recommends retaining PowerShell logs for at least 180 days and monitoring for their deletion or disabling.

The PowerShell log sources and what each records

There are four distinct sources. They overlap, but each answers a different question, and the SOC usually needs at least two of them.

SourceWhere it landsWhat it recordsMain detection use
Script block loggingMicrosoft-Windows-PowerShell/Operational (Windows PowerShell); PowerShellCore/Operational (PowerShell 7)Script input as it is compiled, event 4104. Optional invocation start and stop events 4105 and 4106.Content-based detection, deobfuscated commands, hunting
Module loggingWindows PowerShell log in Event Viewer (Windows PowerShell)Pipeline execution events for the modules you specifyWhich cmdlets ran, with parameters, for selected modules
TranscriptionText files, by default in each user's My Documents folder, or a configured OutputDirectoryInput and output of sessions, with optional invocation headersInvestigation context, seeing what the operator saw
Engine and provider lifecycle eventsWindows PowerShell classic logEngine, provider and (optionally) command start, stop and errorsHost and version context, session start times

Microsoft's Group Policy settings reference states that the Turn on PowerShell Script Block Logging setting "enables logging of all PowerShell script input to the Microsoft-Windows-PowerShell/Operational event log", and that Turn on Module Logging records "pipeline execution events for the specified modules in the Windows PowerShell log in Event Viewer".

Script block logging

Event 4104 carries the message "Creating Scriptblock text (%1 of %2)" at Verbose level, according to Microsoft's PowerShell the Blue Team post. The "%1 of %2" pattern matters: it tells you a script has been split into parts. If you enable Script Block Invocation Logging as well, PowerShell writes 4105 and 4106 events marking the start and completion of each script block invocation. Microsoft notes that invocation logging "generates a high volume of event logs", so most SOCs leave it off and rely on 4104.

Because 4104 records the script text PowerShell processes, rather than only the process command line, it is usually a better place to match content than process creation events. Test this against your own obfuscation samples: how much is exposed depends on how the script is built.

Automatic logging of suspicious script blocks

Microsoft states that "PowerShell automatically logs script blocks when they have content often used by malicious scripts". This means some 4104 events appear even on hosts where script block logging has not been switched on through policy. Treat any such event as a high-priority signal, and treat a host that produces them but has no other PowerShell telemetry as a logging coverage gap to close.

Module logging

Module logging is controlled per module. Each module object has a LogPipelineExecutionDetails property; the Turn on Module Logging policy sets it to true for listed modules, with wildcards supported, and then the value cannot be changed in session. Microsoft's about_Eventlogs topic explains the precedence: User Configuration policy overrides Computer Configuration policy, which overrides the module property. Module logging shows the cmdlets and parameters that actually ran, which complements script block content when attackers build commands dynamically.

Transcription

Transcription writes plain text files rather than events. By default, Microsoft says, PowerShell records transcripts "to each users' My Documents directory, with a filename that includes PowerShell_transcript, along with the computer name and time started". The -IncludeInvocationHeader option "adds an additional header for each command that is invoked", which gives you per-command timestamps. Transcripts include output, so they show what the attacker saw: directory listings, query results and errors.

PowerShell 7 and Windows PowerShell: two sets of channels

Windows PowerShell 5.1 and PowerShell 7 log separately. Microsoft's about_Logging_Windows topic for PowerShell 7 says the event log is in the Application and Services Logs group and is named PowerShellCore, with script block events written to PowerShellCore/Operational. Event 4104 there uses Level Verbose, Opcode Create, Task CommandStart and Keyword Runspace.

Configuration also differs:

  • Windows PowerShell policy lives under Computer Configuration or User Configuration, Administrative Templates, Windows Components, Windows PowerShell. Computer Configuration takes precedence where both apply.
  • PowerShell 7 policy appears under Administrative Templates, PowerShell Core. Microsoft documents the registry value for script block logging as EnableScriptBlockLogging under HKLM:\Software\Policies\Microsoft\PowerShellCore\ScriptBlockLogging. The same option can be set in powershell.config.json.
  • On Windows, the PowerShell 7 event provider has to be registered with RegisterManifest.ps1 in $PSHOME, from an elevated prompt, before events appear. Microsoft advises unregistering before updating PowerShell.

The practical consequence is simple. Inventory which hosts have PowerShell 7 installed, confirm the provider is registered and the PowerShell Core policy is applied, and add PowerShellCore/Operational to your collection configuration. A detection estate that only reads Microsoft-Windows-PowerShell/Operational has a blind spot wherever pwsh.exe is in use.

Collecting the logs without losing them

Collection is where most PowerShell telemetry programmes quietly fail. Script blocks can be large, and the Operational channels are busy on administration hosts.

  • Size the channels. Default local log sizes roll over quickly on servers with heavy automation. Increase the maximum size of the Operational channels so events survive until the forwarder collects them.
  • Forward centrally. Use Windows Event Forwarding or your agent of choice; our Windows Event Forwarding Guide covers subscription design. Include both the Windows PowerShell and PowerShellCore channels.
  • Protect transcripts. If you set OutputDirectory to a shared location, Microsoft advises limiting access "to prevent users from viewing the transcripts of other users or computers". Make the share write-only for clients, and collect from it into a store attackers on the endpoint cannot alter.
  • Retain long enough. CISA's #StopRansomware Guide recommends enabling the PowerShell Windows Event and PowerShell Operational logs, retaining them for at least 180 days, and monitoring for their deletion or disabling.
  • Do not trust the classic log for audit. Microsoft's about_Eventlogs topic warns that the Windows PowerShell log is not designed to be secure: users can read and write it, and a malicious user could record false data or suppress logging. Use it for context, not as your sole evidence.

Protected Event Logging and the SIEM

Script blocks sometimes contain secrets: connection strings, API keys or passwords typed into scripts. Protected Event Logging encrypts that content using the IETF Cryptographic Message Syntax standard. It is enabled under Administrative Templates, Windows Components, Event Logging, Enable Protected Event Logging, and needs a certificate with the Document Encryption enhanced key usage (1.3.6.1.4.1.311.80.1) and either Data Encipherment or Key Encipherment. Microsoft's guidance is clear that "the private key shouldn't be deployed to the machines logging events".

Microsoft recommends enabling Protected Event Logging when script block logging is used for anything other than diagnostics. The trade-off for the SOC is that encrypted content cannot be matched by a SIEM rule unless it is decrypted first. Decide where decryption happens (a hardened collector that holds the private key, using Unprotect-CmsMessage), treat that collector and its key as a privileged non-human identity, and document who can read decrypted output.

Reading 4104 events: fragments, reassembly and noise

Microsoft notes that for long script blocks "Windows PowerShell breaks the script into multiple parts". Each part is its own 4104 event with the same script block ID and a position marker. A rule that searches each event independently will miss an indicator that straddles two parts, and will report the same script many times.

Reassemble before you match. Microsoft's own example sorts the fragments by the first property and joins the text property. An illustrative local version for an investigation:

$created = Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104 } | Where-Object { $_.Message -like '*<ScriptBlockId>*' }
$sorted = $created | Sort-Object { $_.Properties[0].Value }
$merged = -join ($sorted | ForEach-Object { $_.Properties[2].Value })

In the SIEM, do the equivalent at ingest or in a scheduled job: group by host and script block ID, order by fragment number, concatenate the text, then run content rules against the merged script. Store both the fragments (for evidence) and the merged text (for detection).

Expect noise. Management agents, configuration tools, monitoring products and PowerShell's own modules generate large volumes of benign 4104 events. Build an allow list keyed on host role, account and a stable hash of the merged script text, never on the script path alone, which attackers can imitate.

What to detect: high-value detection patterns

The table below lists detection ideas that map to MITRE ATT&CK T1059.001 PowerShell and related techniques. They are starting points, not finished rules, and every one needs tuning against your own baseline.

PatternLog sourceWhy it matters
Automatically logged suspicious script block4104 on hosts without full logging policyPowerShell itself judged the content suspicious
Heavy obfuscation in merged script text: long Base64 strings, string concatenation and character-code building, unusual casingMerged 4104Maps to T1027 Obfuscated Files or Information
Download and in-memory execution in one script blockMerged 4104, module loggingCommon loader pattern for precursor malware
Attempts to change logging, AMSI or Defender settings from script4104, module loggingDefence impairment before the main payload
Commands that delete shadow copies or change recovery settings4104, transcriptionMaps to T1490 Inhibit System Recovery, a ransomware precursor
Directory and domain enumeration from a non-administrative host or account4104, module loggingReconnaissance before lateral movement
Remote execution to many hosts in a short window4104 on source host, Operational logs on targetsLateral movement, or a compromised automation account
PowerShell 7 activity on a host with no PowerShellCore events collectedEndpoint inventory compared with SIEM ingestionCoverage gap or deliberate evasion

CISA's response checklist lists "unexpected PowerShell or PsTools use" among the signs to hunt for in a ransomware investigation, and names PowerShell scripts among the living-off-the-land persistence methods responders should look for. Those are useful anchors when you prioritise which detections to build first.

Writing content rules

Keep content rules readable and explainable. A good rule states the behaviour in plain words, matches on several weak indicators together rather than one strong string, and excludes known automation by identity, host and script hash. An illustrative structure, in pseudo-query form:

source = merged_4104 AND (contains_any(script, download_terms) AND contains_any(script, execute_in_memory_terms)) AND NOT (account IN automation_allow_list AND script_hash IN approved_hashes)

Replace the term lists with values your threat intelligence team maintains, and review hits weekly for the first month.

Detecting tampering with PowerShell logging

Attackers who know the SOC watches 4104 will try to stop it being written or collected. ATT&CK tracks this as T1685 Disable or Modify Tools, with the Windows event log sub-technique covered in our MITRE ATT&CK T1685.001 Disable or Modify Tools guide.

  • Policy drift. Alert when the script block logging policy value is removed or set to off on a host where it was on. For PowerShell 7 the documented value is EnableScriptBlockLogging under the PowerShellCore policy key.
  • Silence detection. Track the daily 4104 count per host. A host that normally produces events and suddenly produces none, while still sending other Windows logs, needs a look.
  • Channel clearing or disabling. CISA specifically recommends monitoring PowerShell logs for deletion or disabling. Alert on log clear events and on the Operational channel being disabled.
  • Downgrade and alternative hosts. Script content run through older engines or custom hosts may bypass the controls you rely on. The PowerShell Security Guide covers removing PowerShell 2.0; in detection terms, alert on its use where it still exists.
  • Transcript directory changes. Alert when OutputDirectory policy changes or when the transcript share stops receiving files from a host.

Where non-human identities fit

In most estates the majority of PowerShell runs under identities that are not people: service accounts, scheduled tasks, deployment pipelines, configuration management agents, managed identities on cloud hosts and, increasingly, AI agents that call shell tools. That makes PowerShell telemetry one of the best sources for spotting a compromised non-human identity.

  • Baseline per identity. For each automation account, record which hosts it runs on, which scripts (by merged-text hash) it runs and at what times. Alert on a new host, a new script or an unusual hour.
  • Watch for interactive use of service accounts. Transcripts and 4104 events showing exploratory commands, typos and repeated enumeration under a service account suggest a person has taken it over.
  • Look for secrets in script blocks. Hard-coded credentials in 4104 text are both a finding (rotate them and move them to a vault) and a reason to adopt Protected Event Logging. Our Windows Event Log Guide covers related account and logon events to correlate with.
  • Remote management paths. PowerShell Remoting and WinRM are how automation reaches servers at scale; the WinRM and JEA security guide covers constraining what those identities can do.

Using transcripts and logs in an investigation

When an alert fires, a practical order of work is:

  1. Pull all 4104 fragments for the script block ID and reassemble them. Record the hash of the merged text.
  2. Search the estate for the same hash or distinctive strings to find other hosts that ran it.
  3. Pull the matching transcript, if one exists, to see output: what the script found, what failed, and whether the attacker adapted.
  4. Check module logging for the cmdlets and parameters that ran, especially where scripts built commands dynamically.
  5. Correlate with logon and process events to identify the account, source host and parent process. A service account launching PowerShell from an unexpected parent is a strong signal.
  6. If Protected Event Logging is in use, decrypt only on the designated collector, and record who accessed the decrypted content.

For ransomware cases, feed findings into the wider response process in the Ransomware Response and Recovery Guide.

Framework mapping

FrameworkReferenceHow this guide applies
MITRE ATT&CKT1059.001 PowerShellScript block and module logging are the primary data sources for this technique
MITRE ATT&CKT1027 Obfuscated Files or InformationMerged 4104 text exposes decoded content
MITRE ATT&CKT1685 Disable or Modify ToolsTamper and silence detections
MITRE ATT&CKT1490 Inhibit System RecoveryRansomware precursor detections in script content
NIST SP 800-53 Rev. 5AU-12 Audit Record Generation; AU-11 Audit Record Retention; SI-4 System MonitoringEnable logging, retain it, and monitor it

Common failure patterns

  • Collecting only Microsoft-Windows-PowerShell/Operational and missing PowerShellCore/Operational on hosts with PowerShell 7.
  • Enabling the PowerShell 7 policy but never registering the event provider, so nothing is written.
  • Matching rules against single 4104 fragments, missing indicators split across parts and creating duplicate alerts.
  • Log channels left at default size on busy servers, so events roll over before collection.
  • Transcripts written to each user's My Documents folder, where an attacker on the host can read or delete them.
  • Broad allow lists by script path or by account alone, which attackers exploit by reusing trusted names or stolen automation credentials.
  • Turning on Protected Event Logging without planning decryption, so the SIEM ingests unreadable content.
  • Treating the classic Windows PowerShell log as tamper-proof evidence despite Microsoft's warning.

Practitioner checklist

  • Script block logging is enabled by policy for Windows PowerShell and PowerShell 7 on every Windows endpoint and server.
  • The PowerShell 7 event provider is registered on every host where pwsh is installed.
  • Both Operational channels and the classic Windows PowerShell log are forwarded centrally, with sizes increased on busy hosts.
  • Module logging is enabled for the modules your detections rely on.
  • Transcription writes to a restricted, centrally collected location with invocation headers on.
  • 4104 fragments are reassembled by script block ID before content rules run.
  • Automatically logged suspicious script blocks raise a high-priority alert.
  • Tamper detections cover policy removal, channel clearing and per-host silence.
  • Each automation and service account has a PowerShell baseline, and deviations alert.
  • Protected Event Logging is enabled, with decryption on a hardened collector whose key is managed as a privileged secret.
  • PowerShell logs are retained for at least 180 days, in line with CISA's recommendation.

Standards and references

Related NHI Mgmt Group resources: PowerShell Security Guide · Okta System Log Detection Guide · Windows Event Forwarding Guide · Sysmon Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.