PowerShell for System Administration & Cybersecurity
PowerShell is a powerful scripting language and command-line shell built on .NET. It's essential for Windows system administration, automation, and security testing. This cheat sheet covers the most commonly used commands and techniques.
📌 Attribution: This cheat sheet is adapted from The Art of Hacking (h4cker) repository by Omar Santos. The original content is licensed under MIT License.
📋 Table of Contents
Basic Commands
Getting Help
Get-Help
Display help information for cmdlets
Get-Help Get-Process
Get-Help Get-Process -Full
Get-Help Get-Process -Examples
Get-Help Get-Process -Online
Get-Command
Search and discover available commands
Get-Command *network*
Get-Command -Verb Get
Get-Command -Noun Service
Basic Cmdlets
Get-Process
List all running processes
Get-Process
Get-Process -Name chrome
Get-Process | Sort-Object CPU -Descending
Get-Service
List Windows services
Get-Service
Get-Service | Where-Object {$_.Status -eq "Running"}
Start-Service -Name "ServiceName"
Stop-Service -Name "ServiceName"
Pipeline & Filtering
Chain commands and filter objects
Get-Process | Where-Object {$_.CPU -gt 100}
Get-Service | Select-Object Name, Status
Get-ChildItem | Measure-Object -Property Length -Sum
Variables and Data Types
# Variables
$name = "Admin"
$age = 25
$isAdmin = $true
# Arrays
$ports = @(21, 22, 80, 443)
$ports[0] # Access element
$ports += 8080 # Add element
# Hash tables
$user = @{
Name = "Admin"
Role = "Administrator"
}
$user["Name"] # Access value
# Special variables
$PSVersionTable # PowerShell version
$env:USERNAME # Current username
$env:COMPUTERNAME # Computer name
$PWD # Current directory
Control Flow
Conditional Statements
if ($age -gt 18) {
Write-Host "Adult"
} elseif ($age -eq 18) {
Write-Host "Just turned adult"
} else {
Write-Host "Minor"
}
# Comparison operators: -eq, -ne, -gt, -lt, -ge, -le, -like, -match
Loops
# For loop
for ($i = 0; $i -lt 10; $i++) {
Write-Host "Count: $i"
}
# ForEach loop
foreach ($port in $ports) {
Write-Host "Port: $port"
}
# ForEach-Object (pipeline)
Get-Process | ForEach-Object {
Write-Host $_.Name
}
# While loop
while ($count -lt 5) {
Write-Host "Count: $count"
$count++
}
Functions
# Basic function
function Get-Greeting {
Write-Host "Hello World"
}
# Function with parameters
function Get-Sum {
param(
[int]$a,
[int]$b
)
return $a + $b
}
# Advanced function with validation
function Test-Port {
param(
[Parameter(Mandatory=$true)]
[string]$ComputerName,
[Parameter(Mandatory=$true)]
[int]$Port
)
try {
$tcpClient = New-Object System.Net.Sockets.TcpClient
$tcpClient.Connect($ComputerName, $Port)
$tcpClient.Close()
return $true
} catch {
return $false
}
}
File Operations
Get-ChildItem
List files and directories
Get-ChildItem
Get-ChildItem -Recurse
Get-ChildItem -Filter *.txt
Get-ChildItem -Include *.exe -Recurse
New-Item
Create files and directories
New-Item -ItemType Directory -Path "C:\Test"
New-Item -ItemType File -Path "C:\test.txt"
"Content" | Out-File "C:\test.txt"
Get-Content / Set-Content
Read and write file contents
Get-Content "C:\file.txt"
"New content" | Set-Content "C:\file.txt"
"Append" | Add-Content "C:\file.txt"
Copy-Item / Move-Item / Remove-Item
Copy, move, and delete files
Copy-Item "source.txt" "dest.txt"
Copy-Item "C:\Source\" "C:\Dest\" -Recurse
Move-Item "source.txt" "dest.txt"
Remove-Item "file.txt"
Remove-Item "C:\Folder\" -Recurse -Force
Get-FileHash
Calculate file hash
Get-FileHash "file.exe" -Algorithm SHA256
Get-FileHash "file.exe" -Algorithm MD5
Select-String
Search for patterns in files
Select-String -Path "*.txt" -Pattern "password"
Get-ChildItem -Recurse | Select-String "API_KEY"
Network Operations
Test-NetConnection
Test network connectivity and ports
Test-NetConnection google.com
Test-NetConnection 192.168.1.1 -Port 80
Test-NetConnection google.com -TraceRoute
Get-NetIPConfiguration
Get network adapter configuration
Get-NetIPConfiguration
Get-NetIPAddress
Get-NetAdapter
Resolve-DnsName
Perform DNS resolution
Resolve-DnsName google.com
Resolve-DnsName -Name domain.com -Type MX
Resolve-DnsName -Name domain.com -Type TXT
Invoke-WebRequest
Make HTTP/HTTPS requests
Invoke-WebRequest -Uri "https://api.example.com"
$response = Invoke-WebRequest -Uri "https://example.com"
$response.StatusCode
Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip"
Invoke-RestMethod
Work with REST APIs
$data = Invoke-RestMethod -Uri "https://api.example.com/data"
$headers = @{"Authorization" = "Bearer TOKEN"}
Invoke-RestMethod -Uri "https://api.example.com" -Headers $headers
💡 Port Scanning Example: Use Test-NetConnection in a loop to scan ports. For production use, consider specialized tools like nmap.
System Information
Get-ComputerInfo
Get detailed computer information
Get-ComputerInfo
Get-ComputerInfo | Select-Object CsName, OsName, OsVersion
Get-CimInstance
Query WMI/CIM for system details
Get-CimInstance Win32_OperatingSystem
Get-CimInstance Win32_Processor
Get-CimInstance Win32_PhysicalMemory
Get-CimInstance Win32_LogicalDisk
Get-CimInstance Win32_BIOS
Get-HotFix
List installed Windows updates
Get-HotFix
Get-HotFix | Sort-Object InstalledOn -Descending
Get-HotFix -Id KB5001234
Environment Variables
Access system environment variables
Get-ChildItem Env:
$env:PATH
$env:USERNAME
$env:COMPUTERNAME
Active Directory
Note: Requires the Active Directory PowerShell module. Install with:
Install-WindowsFeature RSAT-AD-PowerShell
Get-ADUser
Query Active Directory users
Import-Module ActiveDirectory
Get-ADUser -Filter *
Get-ADUser -Identity "username"
Get-ADUser -Filter {Name -like "*admin*"}
Get-ADGroup
Query Active Directory groups
Get-ADGroup -Filter *
Get-ADGroup -Identity "Domain Admins"
Get-ADGroupMember -Identity "Domain Admins"
Get-ADComputer
Query Active Directory computers
Get-ADComputer -Filter *
Get-ADComputer -Filter {OperatingSystem -like "*Server*"}
Get-ADDomain
Get domain information
Get-ADDomain
Get-ADForest
Get-ADDomainController -Filter *
Security Commands
User & Group Management
Local User Management
Manage local users and groups
Get-LocalUser
New-LocalUser -Name "testuser" -Password (ConvertTo-SecureString "P@ss" -AsPlainText -Force)
Set-LocalUser -Name "testuser" -Password (ConvertTo-SecureString "NewP@ss" -AsPlainText -Force)
Remove-LocalUser -Name "testuser"
Local Group Management
Manage local group membership
Get-LocalGroup
Get-LocalGroupMember -Group "Administrators"
Add-LocalGroupMember -Group "Administrators" -Member "testuser"
Remove-LocalGroupMember -Group "Administrators" -Member "testuser"
Firewall
Windows Firewall Management
Configure Windows Firewall
Get-NetFirewallProfile
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
Get-NetFirewallRule
New-NetFirewallRule -DisplayName "Allow Port 80" -Direction Inbound -LocalPort 80 -Protocol TCP -Action Allow
Remove-NetFirewallRule -DisplayName "Allow Port 80"
Event Logs
Event Log Analysis
Query and analyze Windows Event Logs
Get-EventLog -LogName Security -Newest 10
Get-WinEvent -LogName Application -MaxEvents 10
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4624}
Clear-EventLog -LogName Application
Registry
Registry Operations
Read and modify Windows Registry
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"
Set-ItemProperty -Path "HKLM:\SOFTWARE\MyApp" -Name "Setting" -Value "Value"
New-Item -Path "HKLM:\SOFTWARE\MyApp"
Remove-Item -Path "HKLM:\SOFTWARE\MyApp" -Recurse
Post-Exploitation & Reconnaissance
⚠️ Warning: These commands are for authorized security testing and educational purposes only. Unauthorized access to systems is illegal.
System Reconnaissance
Basic Enumeration
Gather system and network information
whoami
whoami /priv
whoami /groups
systeminfo
ipconfig /all
Get-NetIPConfiguration
Privilege Check
Check current privileges and admin status
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
Write-Host "Is Admin: $isAdmin"
Credential Access
WiFi Password Extraction
Extract saved WiFi passwords
netsh wlan show profiles
netsh wlan show profile name="WiFiName" key=clear
Search for Credentials
Search files for passwords and credentials
Get-ChildItem -Path C:\ -Include *.txt,*.xml,*.ini,*.config -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern "password"
Privilege Escalation
Unquoted Service Paths
Find services with unquoted paths
Get-WmiObject Win32_Service | Where-Object {$_.PathName -notlike '*"*' -and $_.PathName -like '* *'}
Scheduled Tasks
Enumerate scheduled tasks
Get-ScheduledTask
Get-ScheduledTask | Where-Object {$_.TaskPath -notlike "\Microsoft*"}
Anti-Forensics
Clear Event Logs
Clear Windows Event Logs
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
Clear PowerShell History
Remove PowerShell command history
Clear-History
Remove-Item (Get-PSReadlineOption).HistorySavePath
📚 Additional Resources:
• Official PowerShell Documentation
• PowerShell Gallery
• The Art of Hacking Repository
• Explore All PowerShell Commands →
• Official PowerShell Documentation
• PowerShell Gallery
• The Art of Hacking Repository
• Explore All PowerShell Commands →