On this page

PowerShell Logging Strategies Guide

Updated on June 22, 2026

Enrico Hochkoeppler Profile

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:

Limitations:

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:

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:

Best practices for transcription:

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:

When Start-Transcript might be appropriate:

Building a Professional Write-Log Function​

A professional logging function provides structured, timestamped, and level-aware logging.

Core requirements for a Write-Log function:

  1. Structured content — all log file lines must be structured content, not loose text messages
  2. Timestamps — the time should be recorded for each log entry
  3. Log levels — support Info, Warning, Error, and Debug levels
  4. Configurable output — decide at runtime whether messages display, and to what stream they are written
  5. 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:

Enabling via Registry:

2. Use Log Rotation and Size Limits​

Module and script block logging can create large log files. Implement log rotation to prevent disk exhaustion:

3. Centralize Log Collection​

In enterprise environments, centralize logs to a SIEM or log management solution:

4. Implement Least Privilege for Log Access​

5. Avoid Excessive Logging​

6. Performance Considerations​

7. Add Context to Log Entries​

Each log entry should include:


Summary​

Effective PowerShell logging requires a multi-layered approach combining native Windows logging with script-level instrumentation.

Native logging (enable all three):

Script-level logging:

Best practices:

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!

Buy Me a Coffee

Previous

Comment-Based Help

Next

Input Validation