← All cheat sheets

POWERSHELL

Plain-text reference · 10 KB. Read it, search it (Ctrl-F) or print it.

Windows PowerShell: Modern command-line shell and scripting language.
Essential for system administration, automation, and security.

GETTING HELP#

Get-Help command                     # Basic help
Get-Help command -Full               # Full documentation
Get-Help command -Examples           # Show examples
Get-Help command -Online             # Open online docs
Get-Command *keyword*                # Find commands
Get-Alias                            # List all aliases
Update-Help                          # Download latest help

            

FILESYSTEM#

Get-Location                         # Current directory (pwd)
Set-Location C:\path                 # Change directory (cd)
Get-ChildItem                        # List items (ls, dir)
Get-ChildItem -Recurse               # Recursive listing
Get-ChildItem -Hidden                # Include hidden files
Get-ChildItem -Filter *.txt          # Filter by extension
Get-ChildItem -Path C:\ -Recurse -Include *.log

New-Item file.txt -ItemType File     # Create file
New-Item folder -ItemType Directory  # Create folder
Remove-Item file.txt                 # Delete file
Remove-Item folder -Recurse -Force   # Delete folder recursively
Copy-Item src dest                   # Copy file
Copy-Item src dest -Recurse          # Copy folder
Move-Item src dest                   # Move/rename
Rename-Item old new                  # Rename

FILE CONTENT#

Get-Content file.txt                 # Read file (cat)
Get-Content file.txt -Tail 10        # Last 10 lines
Get-Content file.txt -Wait           # Follow file (tail -f)
Get-Content file.txt -TotalCount 5   # First 5 lines
Set-Content file.txt "text"          # Write to file
Add-Content file.txt "text"          # Append to file
Clear-Content file.txt               # Empty file

FILE HASHES#

Get-FileHash file.exe                # SHA256 (default)
Get-FileHash file.exe -Algorithm MD5
Get-FileHash file.exe -Algorithm SHA1
Get-FileHash file.exe -Algorithm SHA512

PROCESS MANAGEMENT#

Get-Process                          # List processes
Get-Process -Name chrome             # Filter by name
Get-Process -Id 1234                 # Filter by PID
Get-Process | Sort-Object CPU -Descending
Stop-Process -Name notepad           # Kill by name
Stop-Process -Id 1234                # Kill by PID
Stop-Process -Id 1234 -Force         # Force kill
Start-Process notepad.exe            # Start process
Start-Process cmd.exe -Verb RunAs    # Run as admin
Start-Process calc -WindowStyle Hidden

SERVICES#

Get-Service                          # List services
Get-Service -Name wuauserv           # Specific service
Get-Service | Where-Object {$_.Status -eq "Running"}
Start-Service servicename            # Start
Stop-Service servicename             # Stop
Restart-Service servicename          # Restart
Set-Service servicename -StartupType Automatic
Get-Service | Where-Object {$_.StartType -eq "Automatic" -and $_.Status -ne "Running"}

NETWORK#

Test-Connection host                 # Ping
Test-Connection host -Count 4        # 4 pings
Test-NetConnection host -Port 443    # Port check
Test-NetConnection host -TraceRoute  # Traceroute
Get-NetIPAddress                     # IP configuration
Get-NetIPConfiguration               # Full network config
Get-NetAdapter                       # Network adapters
Get-NetTCPConnection                 # Active connections
Get-NetTCPConnection -State Listen   # Listening ports
Get-NetTCPConnection -LocalPort 80   # Specific port
Resolve-DnsName domain.com           # DNS lookup
Get-DnsClientCache                   # DNS cache
Clear-DnsClientCache                 # Flush DNS

DOWNLOAD FILES#

Invoke-WebRequest -Uri url -OutFile file
(New-Object Net.WebClient).DownloadFile($url, $path)
Invoke-RestMethod -Uri api_url       # GET JSON API
Invoke-RestMethod -Uri url -Method POST -Body $json

USERS & GROUPS#

Get-LocalUser                        # Local users
Get-LocalUser | Select Name,Enabled,LastLogon
Get-LocalGroup                       # Local groups
Get-LocalGroupMember Administrators  # Group members
New-LocalUser "user" -Password $securePass
Remove-LocalUser "user"
Add-LocalGroupMember -Group "Administrators" -Member "user"
Get-ADUser -Filter *                 # AD users (RSAT)
Get-ADGroup -Filter *                # AD groups
Get-ADGroupMember "Domain Admins"

REGISTRY#

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion
Set-ItemProperty -Path "HKLM:\path" -Name "key" -Value "value"
New-Item -Path "HKLM:\Software\NewKey"
Remove-Item -Path "HKLM:\Software\NewKey" -Recurse
Get-ChildItem HKLM:\Software -Recurse | Select-String "search"

# Registry hives
HKLM:                                # HKEY_LOCAL_MACHINE
HKCU:                                # HKEY_CURRENT_USER
HKU:                                 # HKEY_USERS (mount first)
HKCR:                                # HKEY_CLASSES_ROOT

EVENT LOGS#

Get-EventLog -LogName System -Newest 10
Get-EventLog -LogName Security -Newest 100
Get-EventLog -LogName Application -EntryType Error
Get-WinEvent -LogName Security -MaxEvents 50
Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624}
Get-WinEvent -FilterHashtable @{LogName='System';Level=2}

# Common Event IDs
# 4624 - Successful logon
# 4625 - Failed logon
# 4648 - Logon using explicit credentials
# 4672 - Admin logon
# 4688 - Process creation
# 4697 - Service installed

SCHEDULED TASKS#

Get-ScheduledTask                    # List tasks
Get-ScheduledTask -TaskName "name"   # Specific task
Get-ScheduledTaskInfo -TaskName "name"
Start-ScheduledTask -TaskName "name"
Stop-ScheduledTask -TaskName "name"
Disable-ScheduledTask -TaskName "name"
Enable-ScheduledTask -TaskName "name"
Unregister-ScheduledTask -TaskName "name"

FIREWALL#

Get-NetFirewallProfile                # Firewall status
Set-NetFirewallProfile -Profile Domain -Enabled True
Get-NetFirewallRule                  # List rules
Get-NetFirewallRule -Enabled True    # Active rules
New-NetFirewallRule -DisplayName "Block" -Direction Inbound -Action Block
Remove-NetFirewallRule -DisplayName "Block"

SEARCHING#

Select-String "pattern" file.txt     # Grep equivalent
Select-String "pattern" *.log -Recurse
Get-ChildItem -Recurse | Select-String "password"
Get-ChildItem -Path C:\ -Recurse -Include *.txt -ErrorAction SilentlyContinue

# Find files
Get-ChildItem -Path C:\ -Recurse -Name "*.exe" -ErrorAction SilentlyContinue
Get-ChildItem -Path C:\ -Recurse -Filter "flag.txt"

PIPELINE & FILTERING#

command | Where-Object {$_.Property -eq "value"}
command | Select-Object Property1, Property2
command | Sort-Object Property
command | Sort-Object Property -Descending
command | Format-Table -AutoSize
command | Format-List
command | Out-File output.txt
command | Export-Csv output.csv
command | ConvertTo-Json
command | Measure-Object                # Count

# Where-Object shorthand
command | ? {$_.Name -like "*pattern*"}

# Comparison operators
-eq                                  # Equal
-ne                                  # Not equal
-gt                                  # Greater than
-lt                                  # Less than
-ge                                  # Greater or equal
-le                                  # Less or equal
-like                                # Wildcard match
-notlike                             # Wildcard not match
-match                               # Regex match
-contains                            # Array contains

EXECUTION POLICY#

Get-ExecutionPolicy                  # Current policy
Get-ExecutionPolicy -List            # All scopes
Set-ExecutionPolicy Bypass -Scope Process
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Set-ExecutionPolicy Unrestricted     # Needs admin

# Bypass for single script
powershell -ExecutionPolicy Bypass -File script.ps1

ENCODING & DECODING#

# Base64 encode
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("text"))

# Base64 decode
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("dGV4dA=="))

# Execute base64 command
powershell -EncodedCommand <base64_string>

# URL encode
[System.Web.HttpUtility]::UrlEncode("text")

CREDENTIALS#

$cred = Get-Credential               # Prompt for creds
$pass = ConvertTo-SecureString "pass" -AsPlainText -Force
$cred = New-Object PSCredential("user", $pass)
Invoke-Command -ComputerName host -Credential $cred -ScriptBlock {command}

REMOTE EXECUTION#

Enter-PSSession -ComputerName host   # Interactive session
Exit-PSSession                       # Exit session
Invoke-Command -ComputerName host -ScriptBlock {Get-Process}
Invoke-Command -ComputerName host -FilePath script.ps1
Invoke-Command -ComputerName host1,host2 -ScriptBlock {command}

# Enable remoting
Enable-PSRemoting -Force

SYSTEM INFO#

Get-ComputerInfo                     # Full system info
$env:COMPUTERNAME                    # Hostname
$env:USERNAME                        # Current user
$env:USERDOMAIN                      # Domain
[Environment]::OSVersion             # OS version
Get-CimInstance Win32_OperatingSystem
Get-CimInstance Win32_ComputerSystem
Get-WmiObject Win32_BIOS             # BIOS info
Get-HotFix                           # Installed patches

USEFUL ONE-LINERS#

# Find large files
Get-ChildItem C:\ -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.Length -gt 100MB} | Sort-Object Length -Descending

# List installed software
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select DisplayName, DisplayVersion

# Find files modified in last 24h
Get-ChildItem -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}

# Check open ports
Get-NetTCPConnection -State Listen | Select LocalAddress,LocalPort,OwningProcess | Sort-Object LocalPort

# Get process with network connections
Get-NetTCPConnection | Select RemoteAddress,RemotePort,@{N='Process';E={(Get-Process -Id $_.OwningProcess).Name}}

# Recursive file search
Get-ChildItem -Path C:\ -Recurse -Include *.txt -ErrorAction SilentlyContinue | Select-String "password"

# Export running services
Get-Service | Where-Object {$_.Status -eq "Running"} | Export-Csv services.csv

# Find scheduled tasks
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"} | Format-Table TaskName,TaskPath

Defensive reference on CyberRamen. Offensive / red-team sheets live on OffensiveRamen.com.