- Courses
- đź’»Programming Languages
- 🪟PowerShell
- PowerShell Scripting at Scale
- Writing Professional Scripts
- Logging Strategies
On this page
PowerShell Logging Strategies Guide
Updated on June 22, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Effective logging is the difference between knowing what happened on a system and guessing. PowerShell offers three complementary native logging mechanisms—module logging, script block logging, and transcription—that together provide complete visibility into PowerShell activity. Module logging (Event ID 4103) captures command invocations and parameters. Script block logging (Event ID 4104) records the actual content of all script blocks processed, capturing obfuscated code and encoded commands. Transcription creates a complete text-based record of every PowerShell session. For script-level logging, a custom Write-Log function with timestamps, log levels, and structured output provides detailed operational context without overwhelming storage. By combining native Windows logging with script-level instrumentation, you build a comprehensive audit trail that supports security monitoring, troubleshooting, and compliance requirements.
Why Native PowerShell Logging Matters​
Consider this scenario: an attacker runs PowerShell with a Base64-encoded command or downloads a script from the Internet and executes it entirely in memory, never touching disk. Process creation logs (Event ID 4688) show powershell.exe ran, but they do not reveal what the payload actually did. The payload executed entirely in memory—no new processes, no files on disk, no additional process creation events.
This is exactly what PowerShell logging captures. Native PowerShell logging provides visibility into activity that process creation events simply cannot see. For security operations, PowerShell logging is considered the second-most important data source after process creation, covering 209 techniques in the MITRE ATT&CK framework.
CISA recommends enabling three complementary logging types: module logging, script block logging, and transcription logging. Each captures different aspects of PowerShell activity, and together they provide complete coverage.
The Three Pillars of PowerShell Logging​
PowerShell offers three complementary logging mechanisms. Security practitioners recommend enabling all of them.
Module Logging (Event ID 4103)​
Module logging captures pipeline execution details. Every time a PowerShell command executes, module logging records what module was used and the command parameters.
What it captures:
- Command invocations
- Pipeline output (can be verbose)
- Module and command names
- Parameters passed to commands
Limitations:
- Can generate significant volume
- Obfuscated commands are logged as-executed (still obfuscated)
Module logging must be enabled for both the session and specific modules. To enable module logging for a specific module in a session:
$module = Get-Module PSReadLine
$module.LogPipelineExecutionDetails = $true
Code explanation: The LogPipelineExecutionDetails property controls whether pipeline execution events for that module are logged. Setting it to $true enables logging for that module in the current session.
Script Block Logging (Event ID 4104)​
Script block logging is the most valuable of the three logging mechanisms. When enabled, PowerShell records the content of all script blocks that it processes.
What it captures:
- Full script content
- Code captured exactly as it enters the engine at compilation time
- Scripts run via
Invoke-Expression, encoded commands, and other dynamic execution (each new script block generates its own 4104 event) - Obfuscated scripts remain obfuscated in the log
How obfuscation is handled: Because the hook fires when a script block is compiled—before the engine unwinds any obfuscation—the code is recorded exactly as it enters the engine. If an obfuscated script then calls Invoke-Expression with a decoded string, that new script block triggers its own separate 4104 event, which may contain readable code.
Suspicious keyword detection: PowerShell's engine has a built-in list of suspicious keywords. Matching any of them automatically generates a warning-level (Level 3) 4104 event, even without script block logging explicitly enabled.
Important consideration: Do not enable script block invocation start/stop events, as this can result in an excessive number of events.
Transcription Logging​
Transcription logging captures records of every PowerShell session, including all input and output. When enabled, transcripts are saved as text files and contain complete records of PowerShell activity, making them extremely valuable for detecting malicious PowerShell usage.
What it captures:
- All commands entered (including Base64-encoded script blocks in memory)
- All output produced
- Complete session records
Best practices for transcription:
- Record timestamps for each entry
- Consider writing transcripts to a remote, write-only network share to ensure defenders are reviewing logs in a secure manner
- Use Group Policy to enable transcription across all systems
- Protect the transcript folder with appropriate security permissions
Viewing PowerShell Event Logs​
PowerShell logs can be viewed using Windows Event Viewer. The event log is located in the Application and Services Logs group and is named PowerShellCore. Windows PowerShell (5.1 and earlier) logs to a different event log named Windows PowerShell.
To enable the PowerShell event provider, run the following command from an elevated PowerShell prompt:
$PSHOME\RegisterManifest.ps1
Script-Level Logging Strategies​
Beyond native Windows logging, scripts should implement their own logging to capture operational details, errors, and context that native logging does not provide.
The Case Against Start-Transcript​
Start-Transcript records all output streams, including error messages, even if they are caught in a try/catch block. While it is simple to use, it is often considered a "cheap and ugly solution" for professional logging.
Why to avoid relying solely on Start-Transcript:
- It captures everything, including verbose output that may not be useful
- It does not provide structured, searchable log entries
- It offers no control over log levels (Info, Warning, Error, Debug)
- It lacks timestamp formatting and log rotation features
When Start-Transcript might be appropriate:
- Quick debugging of interactive sessions
- Temporary logging during incident response
- Environments where no other logging infrastructure exists
Building a Professional Write-Log Function​
A professional logging function provides structured, timestamped, and level-aware logging.
Core requirements for a Write-Log function:
- Structured content — all log file lines must be structured content, not loose text messages
- Timestamps — the time should be recorded for each log entry
- Log levels — support Info, Warning, Error, and Debug levels
- Configurable output — decide at runtime whether messages display, and to what stream they are written
- Single log entry per call — write a single line to the log file every time the function is called
Example Write-Log function:
function Write-Log {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[string]$Message,
[Parameter()]
[ValidateSet('Info', 'Warning', 'Error', 'Debug')]
[string]$Level = 'Info',
[Parameter()]
[string]$LogPath = "C:\Logs\Script.log",
[Parameter()]
[switch]$ConsoleOutput
)
process {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$entry = "[$timestamp] [$Level] $Message"
# Write to log file
Add-Content -Path $LogPath -Value $entry -ErrorAction SilentlyContinue
# Optionally write to console
if ($ConsoleOutput) {
switch ($Level) {
'Error' { Write-Host $entry -ForegroundColor Red }
'Warning' { Write-Host $entry -ForegroundColor Yellow }
'Info' { Write-Host $entry -ForegroundColor White }
'Debug' { Write-Host $entry -ForegroundColor Gray }
}
}
}
}
Code explanation: This function accepts a message and an optional log level. It creates a timestamped, structured log entry and appends it to the specified log file. The -ConsoleOutput switch controls whether messages are also displayed in the console with color coding based on severity. The -ErrorAction SilentlyContinue ensures that logging failures do not break the script.
Using Write-Verbose and Write-Debug​
For debugging output that should not pollute normal console output, use Write-Verbose and Write-Debug. These can be enabled when needed using the -Verbose and -Debug parameters on advanced functions, or by setting $VerbosePreference and $DebugPreference.
Why this matters: These streams allow you to turn on console logging when needed without polluting the console when you do not need it. This keeps normal output clean while still providing debugging information on demand.
Structured Logging with Write-Information​
PowerShell's Write-Information stream (introduced in PowerShell 5.0) provides a way to separate data from diagnostics without breaking the pipeline. You can use Write-Information for logs with tags, creating structured, machine-readable log entries.
Logging Best Practices​
1. Enable All Three Native Logging Types​
Security practitioners recommend enabling module logging, script block logging, and transcription logging. Each captures different aspects of PowerShell activity, and together they provide complete coverage.
Enabling via Group Policy:
- Computer Configuration → Policies → Administrative Templates → Windows Components → Windows PowerShell
- Turn on Module Logging — specify which modules to log
- Turn on PowerShell Script Block Logging — enables script block logging
- Turn on PowerShell Transcription — enables transcription logging
Enabling via Registry:
- Module logging and script block logging can also be enabled through registry settings
2. Use Log Rotation and Size Limits​
Module and script block logging can create large log files. Implement log rotation to prevent disk exhaustion:
- Configure maximum log file size (e.g., 10 MB)
- Implement log rotation (e.g., keep the last 5 log files)
- Archive old logs to a central location
3. Centralize Log Collection​
In enterprise environments, centralize logs to a SIEM or log management solution:
- Use
Get-WinEventto extract security events from Windows Event Logs with precise filtering - Forward PowerShell event logs to a central collector
- Store transcripts on a remote, write-only network share
4. Implement Least Privilege for Log Access​
- Protect transcript folders with appropriate security permissions
- Ensure only authorized personnel can read and delete log files
- Use write-only permissions for applications writing logs
5. Avoid Excessive Logging​
- Do not enable script block invocation start/stop events
- Be selective about which modules to log (log high-value modules like ActiveDirectory, Hyper-V, NetSecurity rather than all modules)
- Consider the volume of logs generated before enabling verbose logging
6. Performance Considerations​
- Collecting messages during script operation using a single I/O operation to create the log file is much more efficient than writing to the log file multiple times
- Avoid logging inside tight loops unless necessary
- Consider asynchronous logging for high-volume scenarios
7. Add Context to Log Entries​
Each log entry should include:
- Timestamp — when the event occurred
- Computer name — which system generated the log
- Script name — which script or function generated the log
- User context — who was running the script (if applicable)
- Log level — severity of the event
Summary​
Effective PowerShell logging requires a multi-layered approach combining native Windows logging with script-level instrumentation.
Native logging (enable all three):
- Module logging (Event ID 4103) — captures command invocations and parameters
- Script block logging (Event ID 4104) — captures the actual content of all script blocks processed
- Transcription logging — creates a complete text-based record of every PowerShell session
Script-level logging:
- Implement a structured
Write-Logfunction with timestamps and log levels - Use
Write-VerboseandWrite-Debugfor debugging output that can be enabled on demand - Consider
Write-Informationfor structured, tag-based logging
Best practices:
- Enable logging via Group Policy for consistent coverage across all systems
- Implement log rotation to prevent disk exhaustion
- Centralize logs to a SIEM for analysis and alerting
- Apply the principle of least privilege to log access
By implementing these strategies, you build a comprehensive audit trail that supports security monitoring, troubleshooting, and compliance requirements. In the words of security practitioners, PowerShell logging is one of the most important data sources you are probably not capturing.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Comment-Based Help
Next
Input Validation
-
Why Native PowerShell Logging Matters
-
The Three Pillars of PowerShell Logging
- Module Logging (Event ID 4103)
- Script Block Logging (Event ID 4104)
- Transcription Logging
- Viewing PowerShell Event Logs
-
Script-Level Logging Strategies
- The Case Against Start-Transcript
- Building a Professional Write-Log Function
- Using Write-Verbose and Write-Debug
- Structured Logging with Write-Information
-
Logging Best Practices
- 1. Enable All Three Native Logging Types
- 2. Use Log Rotation and Size Limits
- 3. Centralize Log Collection
- 4. Implement Least Privilege for Log Access
- 5. Avoid Excessive Logging
- 6. Performance Considerations
- 7. Add Context to Log Entries
-
Summary
