PowerShell Administration
PowerShell is the most powerful tool on Windows — and the most abused attacker tool. The security mechanisms layered around it are in a constant arms race with obfuscation techniques, and understanding that arms race tells you which controls actually work.
An analyst reviewing SIEM alerts finds a string-matching rule firing on PowerShell:
a process launched with -EncodedCommand. They decode the Base64 and find
another layer of Base64. They decode that and find concatenated string fragments. After
four layers of de-obfuscation, they reach the actual command: a download cradle that
fetches a second-stage payload from a remote server.
What the analyst didn't realize was that the string-matching rule they'd been relying on only caught the outermost layer. Had the organization enabled Script Block Logging, the rule wouldn't have needed to exist — the SIEM would have received the fully de-obfuscated script text automatically, before execution, because PowerShell does the de-obfuscation for you. This chapter explains why Script Block Logging is the single most important PowerShell security control, and how each security mechanism in the PowerShell stack works.
The PowerShell Execution Engine: Where Logging Hooks In
PowerShell is not a single executable — it is a runtime built on .NET that evaluates script code through a pipeline of parsing, compilation, and execution stages. Security controls hook into different stages of this pipeline, which determines what they can and cannot see.
PowerShell Execution Pipeline — Security Hook Points
══════════════════════════════════════════════════════════════════════
Script text (obfuscated or plain) enters:
powershell.exe -enc BASE64STRING
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ COMMAND LINE PARSING │
│ Reads arguments: -enc, -Command, -File, etc. │
│ Decodes Base64 for -EncodedCommand │
│ │
│ Security hook: Command line logging (Event 4688 + Sysmon 1) │
│ Sees: the raw command line BEFORE Base64 decode │
│ Limitation: One layer of obfuscation hides the content │
└──────────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ SCRIPT BLOCK COMPILATION │
│ PowerShell parser tokenizes and compiles the script code │
│ All string concatenation, de-obfuscation, and eval() is done │
│ The final, fully-decoded script is compiled to a ScriptBlock │
│ │
│ Security hook: SCRIPT BLOCK LOGGING (Event 4104) ← KEY │
│ Sees: the fully decoded, ready-to-execute script text │
│ Obfuscation is irrelevant — this happens AFTER decoding │
└──────────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ AMSI SCAN │
│ Antimalware Scan Interface called with the script text │
│ AV/EDR scans the fully-decoded text for known-bad patterns │
│ │
│ Security hook: AMSI (not a log — a block/allow decision) │
│ Sees: fully decoded text — same as Script Block Logging │
│ Limitation: Signature-based; novel scripts may pass │
└──────────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ EXECUTION │
│ Script runs. .NET methods invoked. System calls made. │
│ │
│ Security hook: Module Logging (Event 4103) │
│ Sees: each cmdlet and its parameters as they execute │
└─────────────────────────────────────────────────────────────────┘
Script Block Logging: The Most Important Control
Script Block Logging (Event ID 4104) captures the text of every PowerShell script block as it is compiled — after all de-obfuscation has occurred, before execution. This makes obfuscation irrelevant to detection: regardless of how many layers of Base64, string concatenation, or compression the attacker uses, the logging happens after PowerShell has decoded it all.
| Property | Script Block Logging |
|---|---|
| Event Channel | Microsoft-Windows-PowerShell/Operational |
| Event ID | 4104 (ScriptBlock) |
| Enabled By Default | No. Must be enabled via Group Policy or registry. |
| What it captures | The complete text of every compiled script block, including: inline scripts, scripts loaded from files, dynamically generated code (IEX, Invoke-Expression), imported modules |
| What obfuscation does to it | Nothing. The logging occurs after PowerShell de-obfuscates. A Base64-encoded command that downloads Cobalt Strike is logged as the actual download cradle text. |
| Log volume | High — every script block generates events. SIEM must be sized for the volume. Filtering on suspicious keywords (Invoke-Expression, WebClient, DownloadString, etc.) at ingestion is common. |
| Enable via | Group Policy: Computer Config → Admin Templates → Windows Components → Windows PowerShell → Turn on PowerShell Script Block Logging |
AMSI (Antimalware Scan Interface) and Script Block Logging hook at the same point in the PowerShell pipeline. But they are separate systems. AMSI bypasses typically work by patching amsi.dll in memory — specifically, patching the AmsiScanBuffer function to return "clean" regardless of input. This defeats the AV scan that runs through AMSI. But it doesn't patch the Script Block Logging mechanism, which is implemented in the PowerShell engine itself. Script block logging writes to the Windows Event Log via ETW. Disabling ETW or clearing event logs generates its own detectable events. An attacker who bypasses AMSI to run a malicious script still gets that script logged to Event ID 4104. This is why AMSI bypass and script block logging are independent controls — bypassing one doesn't bypass the other.
AMSI: The Scanning Interface
AMSI (Antimalware Scan Interface) is a Windows API introduced in Windows 10 that allows applications to submit content to the installed antimalware product for scanning before use. PowerShell, VBScript, JScript, and other script hosts call AMSI to scan script content before executing it. The AV/EDR product registers an AMSI provider that receives the scan request and returns a verdict.
AMSI Architecture
══════════════════════════════════════════════════════════════════════
Script host (powershell.exe, cscript.exe, wscript.exe)
│
│ Calls AmsiScanBuffer() in amsi.dll
▼
amsi.dll (loaded in the script host process)
│
│ Calls registered AMSI provider (e.g., Windows Defender)
▼
AV/EDR AMSI Provider (running in the same process)
│
│ Scans content against signatures/ML models
│ Returns: AMSI_RESULT_CLEAN or AMSI_RESULT_DETECTED
▼
amsi.dll returns result to script host
│
├── CLEAN: Script executes
└── DETECTED: Script blocked, error thrown
What AMSI scans:
─────────────────────────────────────────────────────────────────
✓ PowerShell script blocks (fully decoded, same as Event 4104)
✓ JScript and VBScript content
✓ .NET assembly reflection (loading assemblies from memory)
✓ COM object instantiation in scripting contexts
✓ XSL script processing
AMSI Bypass (how attackers defeat it):
─────────────────────────────────────────────────────────────────
Since amsi.dll is loaded into the script host's process,
and the process is at Ring 3 (user mode), the script host
can modify its own memory. AMSI bypasses patch amsi.dll
in memory to make AmsiScanBuffer always return CLEAN.
Common bypass pattern:
- Reflectively load amsi.dll into memory
- Locate AmsiScanBuffer function
- Overwrite its first few bytes with "return 0" (AMSI_RESULT_CLEAN)
- Now AmsiScanBuffer never checks content
Detection of AMSI bypass attempts:
✓ Windows Defender detects many known bypass patterns
✓ ETW events for .NET reflection and memory writes
✓ Some EDR products monitor amsi.dll integrity
Constrained Language Mode
Constrained Language Mode (CLM) is a PowerShell execution context that limits the language features available to scripts. In CLM, many of the capabilities that make PowerShell useful to attackers are unavailable: .NET type instantiation, COM object creation, reflection, and direct Win32 API calls.
| Capability | Full Language Mode | Constrained Language Mode |
|---|---|---|
[System.Net.WebClient]::new() |
Works — downloads files, contacts C2 | Blocked — .NET type instantiation restricted |
Add-Type |
Works — compiles and loads .NET assemblies | Blocked — prevents loading custom .NET code |
[Runtime.InteropServices.Marshal] |
Works — direct memory operations | Blocked — prevents P/Invoke and memory manipulation |
$ExecutionContext.InvokeCommand |
Works | Restricted |
| Built-in cmdlets (Get-Process, etc.) | Works | Works — administrative cmdlets still available |
CLM is enforced by AppLocker or WDAC (Windows Defender Application Control) policy. When a script block is compiled, PowerShell checks whether the policy has restricted this execution context, and sets CLM accordingly. Scripts that are explicitly trusted by the policy (signed, in approved locations) run in Full Language Mode; everything else runs in CLM.
CLM doesn't prevent PowerShell from running — it restricts what PowerShell can do. An attacker can still run PowerShell scripts in CLM, but many of the techniques that make PowerShell attractive for post-exploitation — reflective loading, .NET interop, WebClient downloads — become unavailable. The attacker must fall back to other methods: using built-in cmdlets (which are more visible), dropping to cmd.exe (more detectable), or using standalone executables (which break the fileless execution pattern). CLM makes attacker life harder without preventing legitimate administration.
Execution Policy: A Speed Bump, Not a Security Control
PowerShell's execution policy controls which scripts are allowed to run — Restricted (no scripts), AllSigned (only signed scripts), RemoteSigned (local scripts fine, downloaded must be signed), or Unrestricted. This is widely cited as a security control. It is not.
Why Execution Policy Is Not a Security Boundary
══════════════════════════════════════════════════════════════════════
Execution policy can be bypassed trivially:
1. -ExecutionPolicy Bypass flag:
powershell.exe -ExecutionPolicy Bypass -File evil.ps1
(No admin rights needed)
2. Pipe script via stdin:
Get-Content evil.ps1 | powershell.exe -
(Bypasses file-based policy check entirely)
3. Encode as Base64:
powershell.exe -EncodedCommand BASE64OFSCRIPT
(Encoded commands bypass policy checks)
4. Dot-source from a string:
powershell.exe -Command ". evil.ps1"
5. Change policy for current user:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
(No elevation needed to change user-scope policy)
Microsoft's documentation explicitly states:
"The execution policy is not a security system that
restricts user actions. For example, users can easily
bypass a policy by typing the script contents at the
command line."
What execution policy actually is:
─────────────────────────────────────────────────────────────────
It's a safeguard against accidentally running scripts.
Double-clicking a .ps1 file on a machine with Restricted
policy shows an error rather than silently executing.
This is useful for preventing accidental execution.
It has nothing to do with preventing deliberate execution.
The Three PowerShell Logging Controls Compared
Windows offers three distinct PowerShell logging mechanisms, and they are often confused. Each captures different information and has different implications for detection.
| Logging Type | Event ID | What It Logs | Default | Detection Value |
|---|---|---|---|---|
| Script Block Logging | 4104 | Full text of every compiled script block, fully decoded. Includes dynamically generated code. | Off | Highest. Obfuscation-resistant. Core detection source for PowerShell-based attacks. |
| Module Logging | 4103 | Each cmdlet that executes, with its full parameter bindings (actual values passed to each parameter). | Off | High for cmdlet-level visibility. Verbose — generates many events. Supplements Script Block Logging. |
| Transcription Logging | (text file, not Event Log) | Everything typed and output in a PowerShell session, written to a text file. Human-readable session transcript. | Off | Medium. Useful for forensics (human-readable session replay) but stored locally (can be deleted by attacker). |
| Command Line Auditing | 4688 (in Security log) | The command line used to launch powershell.exe. Does NOT include script content — only the command line arguments. | Partial | Low for content (sees obfuscated command line only). High for detecting the invocation itself. |
Detection rules that match on command line strings like -EncodedCommand,
DownloadString, or IEX in Event ID 4688 are catching the least
sophisticated attackers — those who don't bother with more than one layer of obfuscation.
Any competent attacker encodes their command. -EncodedCommand by itself tells
you a script was encoded; it doesn't tell you what the script does. Script Block Logging
(Event 4104) tells you exactly what the script does, regardless of encoding. If you have
to choose one PowerShell logging control, choose Script Block Logging. Command line auditing
is useful for detecting the invocation; Script Block Logging is useful for detecting the
intent.
Q & A
1. Can an attacker running in Constrained Language Mode break out to Full Language Mode?
It depends on how CLM is enforced. If CLM is enforced by WDAC (Windows Defender Application
Control) with kernel-mode policy enforcement, breaking out of CLM is significantly harder —
the policy is enforced at the kernel level, and PowerShell checks the policy honestly.
An attacker running in CLM with WDAC enforcement cannot simply set
$ExecutionContext.SessionState.LanguageMode = "FullLanguage" and expect it to
work. However, if CLM is enforced only by AppLocker (user-mode), there are bypass techniques:
spawning a new PowerShell process from a bypassed context, using the Windows PowerShell 2.0
downgrade (which is CLM-unaware on older systems), or finding a way to execute code in the
context of a trusted script. The key takeaway: WDAC-enforced CLM is meaningful; AppLocker-
only CLM is weaker and more bypassable. The defense is enabling CLM through WDAC kernel-mode
policy on machines where it matters (privileged access workstations, sensitive servers) rather
than relying on AppLocker alone.
2. What happens when PowerShell Script Block Logging is enabled and an attacker runs a highly obfuscated script?
The attacker's obfuscation work is wasted. Here's what happens step by step: The attacker
runs powershell.exe -enc [layers of base64/concatenation/compression]. PowerShell
parses the command line and decodes the first layer (Base64). If the decoded content is a
further-obfuscated script, PowerShell must execute that script — and to execute it, it must
compile it as a ScriptBlock. That ScriptBlock compilation triggers Event 4104 with the content
at that stage. If that script contains Invoke-Expression (IEX) to further decode
and run another layer, the inner content is also compiled as a ScriptBlock — another 4104.
By the final execution stage, every ScriptBlock compiled in the process has been logged, and
the last one contains the actual malicious logic in plaintext. The SIEM receives the deobfuscated
content. Defenders who have Script Block Logging and a SIEM that collects Event 4104 see the
real payload regardless of how many obfuscation layers the attacker used.
3. What is "PowerShell downgrade attack" and does it still work against modern defenses?
Windows ships with PowerShell 2.0 as a compatibility component alongside modern PowerShell.
PowerShell 2.0 predates Script Block Logging, AMSI, and CLM — it has none of these security
controls. An attacker can invoke PowerShell 2.0 with:
powershell.exe -Version 2 -Command "...". In PowerShell 2.0 context: AMSI is
not called, Script Block Logging doesn't fire, CLM is not enforced. This "downgrade attack"
was a significant gap. The mitigations: (1) Disable PowerShell 2.0 via "Windows Features"
— disable ".NET Framework 2.0" and "Windows PowerShell 2.0" in optional features. This
removes the engine entirely. (2) If PowerShell 2.0 is disabled but someone attempts to use
-Version 2, PowerShell will refuse with an error. (3) The process creation of powershell.exe
with "-Version 2" in the command line is itself a detection signal — legitimate administration
almost never requires specifying -Version 2 on modern Windows. As of Windows 10 later builds,
PowerShell 2.0 requires .NET 2.0 framework which is not installed by default, partially
mitigating the attack without explicit removal.
4. What is "PowerShell without powershell.exe" and why does it matter for detection?
PowerShell the language is separate from powershell.exe the executable. The PowerShell runtime is implemented in System.Management.Automation.dll, a .NET assembly. Any .NET application can load this DLL and execute PowerShell script blocks programmatically without ever launching powershell.exe. Attackers use this to bypass detections that rely on seeing powershell.exe in process creation events — if the PowerShell runtime is loaded inside another process, there's no powershell.exe to detect. Tools like p0wnedShell, NPS (Not PowerShell), and various C# loaders implement this technique. The detection implications: (1) AMSI is still called — the PowerShell runtime still invokes AMSI regardless of which process hosts it. (2) Script Block Logging still fires — Event 4104 records are generated by the PowerShell engine, not by powershell.exe specifically. The events appear with the hosting process name, not powershell.exe. (3) Command line auditing (4688) won't see powershell.exe — you'd see the loader process instead. This is why Script Block Logging remains the most reliable PowerShell detection even against "powershell without powershell.exe" techniques.