PowerShell for Red Teamers: Windows Exploitation & Post-Exploitation
Cybersecurity

PowerShell for Red Teamers: Windows Exploitation & Post-Exploitation

by Carter Hayes

$9.99
Genre Cybersecurity
Author Carter Hayes
Format eBook (PDF & EPUB)
Delivery Instant digital download

About This Book

Cybersecurity is a field where practical skill matters more than memorized facts. The threats facing organizations and individuals grow more sophisticated every year, and the best defense is a workforce that understands how attackers actually operate. This book gives you the hands-on knowledge and structured approach you need to move from curiosity to real competence.

The material is designed for people who want real results, not just theory. It explains the concepts behind the tools, walks you through realistic scenarios, and shows you how to apply what you learn in actual testing environments. Whether you are studying for a certification, building a security career, or protecting your own infrastructure, this guide is built to move you forward.

What sets this book apart is its focus on doing the work. Each chapter connects ideas to actions, so you understand not only what a technique does but why it works and when to use it. The exercises and examples are built around tools and situations you are likely to encounter in real assessments, labs, and job roles.

By the time you finish, you will have more than a list of commands. You will understand how attacks fit together, how to spot weak points in a system, and how to explain your findings in a way that helps people fix problems. Those skills are the foundation of a successful career in cybersecurity.

Read a Sample ▸

Not sure yet? Here is the full table of contents and the first chapter, exactly as it appears in the book.

Contents

  • Chapter 1: Red Team PowerShell Foundations
  • Chapter 2: Obfuscation and Evasion Techniques
  • Chapter 3: Initial Access and Payload Delivery
  • Chapter 4: Credential Access and Harvesting
  • Chapter 5: PowerView and Active Directory Reconnaissance
  • Chapter 6: Local Privilege Escalation Strategies
  • Chapter 7: Lateral Movement and Remote Execution
  • Chapter 8: Persistence Mechanisms and Backdoors
  • Chapter 9: Defense Evasion and Anti-Forensics
  • Chapter 10: Network Reconnaissance and Pivoting
  • Chapter 11: Data Exfiltration and Collection
  • Chapter 12: Kerberos Attacks with PowerShell
  • Chapter 13: Fileless Malware and In-Memory Execution
  • Chapter 14: Command and Control with PowerShell
  • Chapter 15: Bypassing Application Whitelisting
  • Chapter 16: PowerShell for Cloud Exploitation
  • Chapter 17: Red Team Operational Tradecraft
  • Chapter 18: Detection Engineering and Blue Team Perspective

18 chapters in the complete book.

Chapter 1: Red Team PowerShell Foundations

PowerShell represents one of the most powerful tools available to Windows administrators, which makes it equally powerful for offensive security practitioners. The very features that enable system administrators to manage thousands of machines efficiently can be leveraged by red teamers to move laterally, execute code, exfiltrate data, and maintain persistence across Windows environments. Understanding PowerShell from an adversarial perspective means viewing it not as a helpful scripting language but as a privileged execution environment with direct access to Windows operating system internals, the .NET framework, and countless administrative APIs.

Microsoft’s transition from traditional command-line scripting to PowerShell fundamentally changed Windows security. Unlike cmd.exe, which passes text between programs and relies heavily on external executables, PowerShell operates on objects and integrates directly with Windows management interfaces. This object-oriented approach gives it unprecedented access to system resources. Active Directory, registry keys, network configurations, and virtually every aspect of Windows functionality. For red teamers, this means a single console provides access to capabilities that previously required multiple tools, custom exploits, or administrative GUI navigation.

As you progress through this book, you’ll discover that PowerShell isn’t just another tool in your arsenal. It’s often the connector between all other techniques. Modern red team operations frequently rely on it for everything from initial reconnaissance to final objectives. However, the defensive community has evolved significantly. Today’s security products scrutinize PowerShell activity more aggressively than almost any other execution vector. Understanding how PowerShell works, how it’s monitored, and how defensive mechanisms attempt to constrain it provides the critical knowledge necessary for developing effective offensive techniques.

Understanding PowerShell Architecture

PowerShell’s architecture differs fundamentally from traditional Windows scripting environments. At its core, PowerShell consists of two primary components: the PowerShell engine and the hosting process. The engine handles cmdlet execution, pipeline processing, and interaction with .NET objects. The hosting process provides the user interface and environment. PowerShell.exe and PowerShell_ISE.exe represent the most common hosts, but the engine can be embedded into any application, including custom-developed red team tools.

This separation between engine and host creates interesting opportunities for offensive operations. Because the engine can be loaded into alternative processes, attackers can execute PowerShell code without launching PowerShell.exe, potentially evading detection mechanisms that monitor process creation. Tools leveraging this approach embed the System.Management.Automation namespace directly into memory, providing full functionality without the telltale signs of traditional execution.

The PowerShell runtime operates within the .NET Common Language Runtime, giving it direct access to the entire framework. This integration means scripts can instantiate .NET objects, call Windows API functions, interact with COM objects, and access unmanaged code through Platform Invocation Services (P/Invoke). For red teamers, this translates to capabilities ranging from network socket programming to direct memory manipulation, all from within a scripting environment that Microsoft explicitly designed for administrative automation.

PowerShell’s remoting capabilities deserve special attention. Built on the Web Services for Management protocol and implemented through Windows Remote Management (WinRM), PowerShell remoting enables command execution across networked systems. By default, WinRM listens on ports 5985 for HTTP and 5986 for HTTPS. Understanding how remoting authenticates, encrypts traffic, and handles sessions matters when planning lateral movement operations. Unlike tools such as PsExec that rely on SMB shares and service creation, PowerShell remoting provides a more covert channel that blends with legitimate administrative traffic.

Execution Policies and Their Limitations

Execution policies represent one of PowerShell’s most misunderstood security features. Many administrators mistakenly view them as security boundaries, when Microsoft explicitly documents them as convenience features designed to prevent accidental script execution. From a technical standpoint, execution policies check whether a script file has a valid digital signature or meets other criteria before allowing it to run. These checks occur at the script file level, not the command level.

The default execution policy on Windows clients is Restricted, which prevents script files from executing but still permits interactive commands in the console. Windows Server systems typically default to RemoteSigned, allowing locally created scripts to run while requiring downloaded scripts to be signed. Other policies include AllSigned, Unrestricted, Bypass, and Undefined, each providing different levels of restriction. However, attackers with sufficient access can trivially bypass every execution policy.

Several straightforward techniques circumvent execution policies entirely. The most direct approach involves launching PowerShell with the -ExecutionPolicy Bypass parameter, which instructs it to ignore policy restrictions for that session. Alternatively, reading script content and piping it to PowerShell’s standard input bypasses file-based policy checks entirely. Commands like Get-Content script.ps1 | PowerShell.exe -NoProfile execute script content without triggering enforcement.

For red teamers, execution policies rarely present genuine obstacles. Instead, they serve as indicators of defensive maturity within target environments. Organizations that rely solely on execution policies for security typically lack comprehensive monitoring and detection capabilities. More sophisticated defenders implement layered controls including application whitelisting, script block logging, and behavioral analytics.

PowerShell Version Differences and Security Implications

PowerShell’s evolution from version 2.0 through the current 7.x releases introduced substantial security improvements that directly impact offensive operations. PowerShell 2.0, released with Windows 7 and Server 2008 R2, lacks virtually all modern security features. It provides no script block logging, no AMSI integration, and no constrained language mode. Critically, PowerShell 2.0 can be explicitly invoked on systems where newer versions are installed by using the -Version 2 parameter, potentially downgrading to an environment without defensive telemetry.

This downgrade attack became so prevalent that Microsoft released updates to limit PowerShell 2.0 availability and enhanced logging to detect version downgrades. Organizations that have removed the PowerShell 2.0 engine entirely have eliminated this attack vector, but many environments retain older versions for compatibility with legacy scripts and management tools. When conducting reconnaissance, identifying which versions are available on target systems provides immediate insight into potential defensive gaps.

PowerShell 3.0 through 4.0 introduced significant functionality improvements but maintained relatively weak security controls by modern standards. Version 5.0, however, marked a turning point with the introduction of comprehensive logging capabilities, AMSI integration, and constrained language mode. These features fundamentally altered the risk calculus for attackers. Script block logging, in particular, captures the actual code executed, including deobfuscated content, making many traditional evasion techniques ineffective against properly configured environments.

PowerShell 5.1 remains the most recent version included with Windows by default and represents the last version built on the full .NET Framework. PowerShell 6.0 and later, now called PowerShell Core, run on .NET Core (later .NET 5+), providing cross-platform compatibility but with reduced Windows-specific functionality. For red team operations primarily targeting Windows environments, version 5.1 typically remains the most relevant. Understanding the security features present in 5.1 and later enables development of techniques that account for modern defensive controls.

Script Block Logging and Detection Telemetry

Script block logging represents one of the most significant defensive improvements in modern PowerShell. When enabled, this feature logs all script blocks executed: not just commands typed interactively, but also code loaded from files, downloaded from the internet, or executed through other automation. The logging occurs in Event ID 4104 under the Microsoft-Windows-PowerShell/Operational event log, providing defenders with detailed visibility into activity.

The sophistication of script block logging extends beyond simple command capture. PowerShell implements automatic deobfuscation before logging, meaning heavily encoded or obfuscated commands are logged in their decoded form. This mechanism defeats many basic obfuscation techniques that attempt to hide malicious intent through string encoding, character substitution, or command fragmentation. When PowerShell executes code containing suspicious patterns, it also enables warning-level logging even if script block logging isn’t configured for all content.

For red teamers, script block logging fundamentally changes operational tradecraft. The traditional approach of downloading and executing scripts directly from memory no longer operates silently. Every cmdlet invocation, every .NET method call, and every system interaction leaves a trail in the event logs. Organizations with centralized log collection and security information and event management systems can detect suspicious activity in near real-time, particularly when monitoring for known offensive frameworks and command patterns.

Several factors influence script block logging’s effectiveness. First, the feature must be explicitly enabled through Group Policy or local configuration. Default Windows installations don’t enable comprehensive logging, leaving many organizations without this telemetry. Second, script block logging generates substantial log volume in environments with heavy PowerShell usage, potentially creating storage and performance concerns. Third, the logs themselves must be protected, forwarded, and monitored to provide security value. Attackers with sufficient privileges may disable logging, clear logs, or modify configurations to reduce detection risk.

Anti-Malware Scan Interface Integration

The Anti-Malware Scan Interface provides real-time scanning of PowerShell script content before execution. Introduced in Windows 10 and Server 2016, AMSI enables antivirus and EDR products to inspect script-based attacks that would otherwise execute entirely in memory without touching disk. When PowerShell prepares to execute code, it passes the content to registered AMSI providers, which can block execution if the content appears malicious.

AMSI operates at multiple layers within PowerShell. It scans commands entered interactively, script content loaded from files, code downloaded from remote sources, and even dynamically generated code through techniques like Invoke-Expression. The interface also captures deobfuscated content, similar to script block logging, preventing simple encoding schemes from bypassing detection. Major antivirus vendors have integrated AMSI support into their products, creating substantial detection capability for script-based attacks.

From an offensive perspective, AMSI represents a significant challenge but not an insurmountable barrier. The interface runs within the PowerShell process space, meaning attackers with code execution can potentially manipulate or disable AMSI functionality. Various bypass techniques have emerged, ranging from simple memory patching to sophisticated manipulation of .NET internals. However, these bypasses often trigger their own detection signatures, creating a cat-and-mouse game between offensive and defensive capabilities.

Understanding AMSI’s architecture helps red teamers develop more resilient techniques. AMSI doesn’t directly block execution; instead, it provides scan results to the calling application, which decides how to respond. PowerShell treats AMSI blocks as errors, preventing script execution but allowing the session to continue. The scan occurs synchronously, meaning performance-intensive scanning could theoretically be exploited. Additionally, AMSI relies on signature-based and heuristic detection, meaning novel techniques or sufficient obfuscation may evade detection until signatures are updated.

Constrained Language Mode and Code Execution Restrictions

Constrained Language Mode restricts PowerShell to a limited subset of functionality designed to prevent arbitrary code execution. When enabled, CLM disallows direct .NET method invocations, Add-Type cmdlets, COM object creation, and various other features that attackers leverage for exploitation. The mode permits basic cmdlets and approved operations while blocking access to potentially dangerous functionality.

Organizations typically enable Constrained Language Mode through AppLocker or Windows Defender Application Control policies that enforce code integrity requirements. When these policies are active, PowerShell automatically enters CLM unless the script or module is explicitly trusted through proper signing. This approach creates a whitelist-based execution model where only approved code runs with full language capabilities.

For red teamers, CLM represents one of the most restrictive security controls. Unlike execution policies or AMSI, which can often be bypassed through technique modifications, CLM fundamentally removes capabilities from the language itself. Standard tactics like invoking Win32 APIs through P/Invoke, instantiating .NET types for memory manipulation, or creating COM objects for lateral movement become impossible within CLM.

However, CLM isn’t universally deployed and contains inherent limitations. Many organizations haven’t implemented the AppLocker or WDAC policies necessary to trigger it. Even in environments with CLM enabled, certain escape paths exist. Trusted scripts and modules can downgrade to Full Language Mode, potentially providing opportunities for abuse. Additionally, CLM only restricts PowerShell itself; attackers can pivot to alternative execution methods like native Windows utilities, scripting languages, or compiled executables.

AppLocker and Application Whitelisting

AppLocker provides Windows with application whitelisting capabilities that control which executables, scripts, Windows Installer files, packaged apps, and DLLs can run on a system. When configured for PowerShell, AppLocker can prevent unauthorized scripts from executing, restrict remoting, and force Constrained Language Mode for untrusted code. Unlike execution policies, AppLocker enforcement occurs at the kernel level through code integrity checks, making it substantially more difficult to bypass.

AppLocker rules can be defined based on file paths, publishers (code signing certificates), or file hashes. Path-based rules allow execution from trusted directories like System32 or Program Files while blocking execution from user-writable locations. Publisher rules permit execution of any software signed by trusted certificates, while hash rules whitelist specific file versions. The combination of these rule types enables granular control over application execution across an environment.

From an offensive standpoint, AppLocker presents significant challenges but also potential weaknesses. Path-based rules often include overly permissive trusted directories where users can write files. Common bypass techniques involve identifying writable folders within trusted paths, such as certain subdirectories of System32, or leveraging trusted Microsoft-signed binaries to proxy command execution. Living Off the Land Binaries represent legitimate Windows executables that can be abused to execute code, potentially bypassing AppLocker restrictions.

Windows Defender Application Control, previously known as Device Guard, provides similar functionality to AppLocker but with more robust enforcement mechanisms. WDAC operates at a lower level in the operating system, providing better protection against kernel-mode threats and sophisticated bypass attempts. Organizations increasingly deploy WDAC for high-security environments, forcing red teamers to adapt techniques or focus on alternate attack vectors.

Setting Up Your Testing Environment

Developing offensive PowerShell capabilities requires a safe, isolated testing environment where you can experiment without risk to production systems or legal consequences. A proper lab should include multiple Windows systems with varying PowerShell versions, different security configurations, and network isolation to simulate realistic target environments. Virtual machines provide the flexibility to snapshot, revert, and clone systems as needed during testing.

Start with at least three Windows virtual machines: one running Windows 10 or 11 as a client workstation, one running Windows Server 2019 or 2022 as a domain controller, and a third server for testing lateral movement and post-exploitation techniques. Configure these with different PowerShell versions where possible, enabling you to test how techniques behave across version differences. Install PowerShell 2.0 on systems where it’s available to understand downgrade attack implications.

Configure varying levels of security controls across your test systems. One should run with minimal protections (execution policies disabled, no AMSI, and no logging enabled) providing a baseline for technique development. A second should implement standard enterprise security: execution policies set to RemoteSigned, AMSI enabled, and script block logging configured. A third should represent a hardened environment with AppLocker or WDAC policies, CLM enforced, and comprehensive monitoring enabled.

Network isolation prevents accidental exposure of offensive tools to production environments and contains any mistakes during testing. Use virtual networking to create isolated VLANs that cannot route to production networks or the internet unless explicitly required. Configure Windows Firewall rules consistently across test systems to simulate enterprise environments where network restrictions may impact exploitation techniques.

Install monitoring and logging tools to understand defensive visibility into your activities. Configure Sysmon to capture detailed process creation, network connections, and file modifications. Enable all available logging mechanisms and forward logs to a centralized collection point. Install an EDR solution in your lab environment to test how commercial security products detect and respond to offensive techniques.

Understanding the Attack Surface

Viewing PowerShell through an adversarial lens reveals multiple attack surfaces. The most obvious involves direct script execution: downloading and running scripts that perform reconnaissance, exploitation, or post-exploitation activities. This approach dominated early offensive usage but has become increasingly risky as defensive capabilities improved. Modern operations require more sophisticated techniques that blend with legitimate activity and minimize forensic artifacts.

Remoting capabilities create another significant attack surface. WinRM, enabled by default on Windows Server systems and increasingly common on workstations, provides authenticated remote command execution with minimal logging compared to alternative remote administration tools. Understanding how to leverage remoting for lateral movement, command execution, and data exfiltration forms a core component of offensive operations.

The integration between PowerShell and .NET opens substantial attack surface through reflection, dynamic code loading, and direct API access. These techniques enable in-memory execution of payloads, avoiding disk writes that trigger antivirus scans. Reflective loading of .NET assemblies, invoking unmanaged code through P/Invoke, and manipulating types all provide powerful capabilities that extend beyond traditional scripting.

The object pipeline itself represents an often-overlooked attack surface. Because PowerShell passes .NET objects between commands rather than text, attackers can leverage object properties and methods in unexpected ways. Understanding how to manipulate objects, access hidden properties, and chain commands creatively enables techniques that evade detection mechanisms focused on command syntax rather than object behavior.

The defensive perspective reveals additional attack surfaces that red teamers must understand to avoid detection. Process creation events, network connections, file system modifications, registry changes, and Windows event logs all generate telemetry that sophisticated defenders monitor for signs of malicious activity. Developing a mental model of what artifacts your techniques create helps you understand detection risk and adjust tradecraft accordingly.

As you continue through this book, keep these foundational concepts in mind. Every technique we explore builds on these principles: understanding how PowerShell works internally, recognizing what defensive controls may be present, and developing approaches that achieve operational objectives while managing detection risk. PowerShell provides extraordinary capabilities for offensive security operations, but success requires more than knowing which commands to run. It demands a deep understanding of the execution environment, defensive architecture, and the subtle interplay between offensive techniques and defensive telemetry.

… and that is just the beginning. The complete book continues from here, instant download, DRM-free, yours to keep.

More by Carter Hayes