PowerShell for Security Analysts Cheatsheet
The PowerShell an analyst runs to investigate a Windows host and the domain around it, question by question: the machine, accounts and the domain, credentials, processes and remote sessions, files, the registry, event logs, PowerShell's own logs, persistence and Defender, then collecting, containing and the account in Entra ID and Exchange Online, plus a live response script, remoting at scale, parsing events, deobfuscation and PowerShell's own security state. 124 questions, each with the command and what its answer does not prove. No account needed.
Before you start
Run these in PowerShell 7.6 in an elevated session on the host, or through Invoke-Command from your own. Each card gives the question it settles, the command, what to read in the result and what the result does not prove. Read the last before acting on an answer.
A live response collection script 1
One script that collects the volatile state first, then the durable artifacts, writes everything to one folder with a transcript, and hashes the results. Run it elevated, from removable media or a share, before containment.
$out = "C:\IR\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HHmmss)"
New-Item -ItemType Directory -Path $out -Force | Out-Null
Start-Transcript -Path "$out\transcript.txt"
# 1. Processes, connections, sessions, DNS cache: these change first
Get-CimInstance Win32_Process |
Select-Object ProcessId, ParentProcessId, Name, ExecutablePath, CommandLine, CreationDate |
Export-Csv -Path "$out\processes.csv" -NoTypeInformation
Get-NetTCPConnection |
Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess |
Export-Csv -Path "$out\tcp.csv" -NoTypeInformation
Get-SmbSession | Export-Csv -Path "$out\smb-sessions.csv" -NoTypeInformation
Get-DnsClientCache | Export-Csv -Path "$out\dns-cache.csv" -NoTypeInformation
Get-NetNeighbor | Export-Csv -Path "$out\arp.csv" -NoTypeInformation
# 2. Persistence and configuration
Get-CimInstance Win32_Service |
Select-Object Name, State, StartMode, StartName, PathName |
Export-Csv -Path "$out\services.csv" -NoTypeInformation
Get-ScheduledTask | Export-Clixml -Path "$out\tasks.xml"
Get-LocalGroupMember -Group "Administrators" |
Export-Csv -Path "$out\local-admins.csv" -NoTypeInformation
Get-MpPreference | Export-Clixml -Path "$out\defender-preferences.xml"
# 3. Logs, exported rather than parsed
wevtutil epl Security "$out\Security.evtx"
wevtutil epl System "$out\System.evtx"
wevtutil epl "Microsoft-Windows-PowerShell/Operational" "$out\PowerShell.evtx"
Stop-Transcript
# 4. Hash everything collected
Get-ChildItem -Path $out -File | Get-FileHash -Algorithm SHA256 |
Export-Csv -Path "$out-hashes.csv" -NoTypeInformationThe machine 7
Settle what you are looking at before reading anything on it: the build, the domain, when it last started and what it runs as a service.
Get-CimInstance Win32_OperatingSystem |
Select-Object Caption, Version, BuildNumber, LastBootUpTime
Get-CimInstance Win32_ComputerSystem |
Select-Object Name, Domain, PartOfDomain, Manufacturer, Model$cv = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
"{0}.{1}" -f $cv.CurrentBuildNumber, $cv.UBR
Get-HotFix | Sort-Object InstalledOn -Descending |
Select-Object -First 5 HotFixID, Description, InstalledOnGet-CimInstance Win32_Service |
Where-Object { $_.PathName -notmatch '^"?C:\\Windows\\' } |
Select-Object Name, State, StartMode, StartName, PathNameGet-NetIPConfiguration |
Select-Object InterfaceAlias, IPv4Address, IPv4DefaultGateway, DNSServerGet-TimeZone | Select-Object Id, BaseUtcOffset
$os = Get-CimInstance Win32_OperatingSystem
"Up since {0:u}, {1:N1} days" -f $os.LastBootUpTime,
((Get-Date) - $os.LastBootUpTime).TotalDays$keys = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
Get-ItemProperty -Path $keys |
Where-Object DisplayName |
Sort-Object InstallDate -Descending |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate -First 30Get-WindowsOptionalFeature -Online |
Where-Object State -eq "Enabled" |
Select-Object FeatureNameAccounts 5
Who can sign in to the host and who controls it, then the events that record changes to either.
Get-LocalGroupMember -Group Administrators |
Select-Object Name, ObjectClass, PrincipalSourceGet-LocalUser | Where-Object Enabled |
Select-Object Name, PasswordLastSet, LastLogon, DescriptionGet-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4720, 4722, 4724, 4738, 4732 } |
Select-Object TimeCreated, Id, MessageGet-LocalGroup | Select-Object Name, Description
"Administrators", "Remote Desktop Users", "Remote Management Users" | ForEach-Object {
$g = $_
Get-LocalGroupMember -Group $g -ErrorAction SilentlyContinue |
Select-Object @{ n = "Group"; e = { $g } }, Name, ObjectClass, PrincipalSource
}Get-LocalUser |
Select-Object Name, Enabled, PasswordRequired, PasswordExpires, PasswordLastSet, LastLogon |
Sort-Object LastLogon -DescendingThe domain 11
Questions about Active Directory rather than one host. These need the ActiveDirectory module, which ships with the Remote Server Administration Tools and on domain controllers.
Get-ADDomainController -Filter * |
Select-Object Name, IPv4Address, Site, OperatingSystem, IsGlobalCatalogGet-ADUser -Filter "Enabled -eq 'True'" -Properties LastLogonDate, PasswordLastSet |
Sort-Object PasswordLastSet -Descending |
Select-Object SamAccountName, PasswordLastSet, LastLogonDateGet-ADUser -LDAPFilter "(servicePrincipalName=*)" -Properties ServicePrincipalName, PasswordLastSet |
Select-Object SamAccountName, Enabled, PasswordLastSet, ServicePrincipalNameGet-ADUser -Filter "DoesNotRequirePreAuth -eq 'True'" -Properties DoesNotRequirePreAuth |
Select-Object SamAccountName, EnabledGet-ADUser -Filter "AdminCount -eq 1" -Properties AdminCount, LastLogonDate |
Select-Object SamAccountName, Enabled, LastLogonDate"Domain Admins", "Enterprise Admins", "Schema Admins", "Administrators" | ForEach-Object {
$g = $_
Get-ADGroupMember -Identity $g -Recursive |
Select-Object @{ n = "Group"; e = { $g } }, SamAccountName, ObjectClass
}Get-ADComputer -Filter "TrustedForDelegation -eq 'True'" -Properties TrustedForDelegation |
Select-Object Name, DNSHostName
Get-ADObject -Filter "msDS-AllowedToDelegateTo -like '*'" -Properties msDS-AllowedToDelegateTo |
Select-Object Name, ObjectClass, msDS-AllowedToDelegateTo$dn = "CN=AdminSDHolder,CN=System," + (Get-ADDomain).DistinguishedName
(Get-Acl -Path "AD:$dn").Access |
Where-Object { $_.ActiveDirectoryRights -match "GenericAll|WriteDacl|WriteOwner" } |
Select-Object IdentityReference, ActiveDirectoryRights, AccessControlTypeGet-ADDefaultDomainPasswordPolicy |
Select-Object MinPasswordLength, LockoutThreshold, LockoutDuration, MaxPasswordAgeGet-ADTrust -Filter * |
Select-Object Name, Direction, TrustType, SIDFilteringQuarantined$domain = (Get-ADDomain).DNSRoot
Get-ADReplicationPartnerMetadata -Target $domain -Scope Domain |
Select-Object Server, Partner, LastReplicationSuccess, LastReplicationResultCredentials on the host 3
What an intruder with administrative rights could take from this machine's memory, and the Kerberos tickets it holds now.
Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" `
-Name UseLogonCredential -ErrorAction SilentlyContinue
Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" |
Select-Object RunAsPPL, LmCompatibilityLevelklist
klist sessionsGet-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" |
Select-Object RunAsPPL, LsaCfgFlags
Get-CimInstance -Namespace root\Microsoft\Windows\DeviceGuard `
-ClassName Win32_DeviceGuard |
Select-Object SecurityServicesRunningProcesses and connections 8
What is running, what started it, and what it is talking to. Collect these first: they change while you work.
Get-CimInstance Win32_Process |
Select-Object ProcessId, ParentProcessId, Name, ExecutablePath, CommandLineGet-CimInstance Win32_Process -Filter "Name = 'rundll32.exe'" |
Invoke-CimMethod -MethodName GetOwner |
Select-Object Domain, UserGet-NetTCPConnection -State Established, Listen |
Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess,
@{ n = "Process"; e = { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name } }Get-DnsClientCache | Select-Object Entry, Type, TimeToLive, DataGet-Process |
Where-Object { $_.Path -match "\\AppData\\|\\Temp\\|\\Users\\Public\\|\\ProgramData\\" } |
Select-Object Id, ProcessName, Path, StartTimeGet-CimInstance Win32_Process |
Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate |
Sort-Object CreationDate$root = 4242
$kids = Get-CimInstance Win32_Process -Filter "ParentProcessId = $root"
$kids | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
Stop-Process -Id $root -ForceGet-NetUDPEndpoint |
Select-Object LocalAddress, LocalPort, OwningProcess,
@{ n = "Process"; e = { (Get-Process -Id $_.OwningProcess).ProcessName } }Network configuration and state 5
What the host thinks the network looks like, which an attacker can change: name resolution, neighbors, routes, proxy and firewall rules.
Get-DnsClientServerAddress -AddressFamily IPv4 |
Select-Object InterfaceAlias, ServerAddressesGet-Content -Path C:\Windows\System32\drivers\etc\hosts |
Where-Object { $_ -notmatch "^\s*#" -and $_.Trim() }Get-NetNeighbor -State Reachable, Stale |
Select-Object IPAddress, LinkLayerAddress, InterfaceAlias
Get-NetRoute -AddressFamily IPv4 |
Where-Object DestinationPrefix -ne "0.0.0.0/0" |
Select-Object DestinationPrefix, NextHop, InterfaceAliasnetsh winhttp show proxy
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" |
Select-Object ProxyEnable, ProxyServer, AutoConfigURLGet-NetFirewallRule -Enabled True -Direction Inbound -Action Allow |
ForEach-Object {
$p = $_ | Get-NetFirewallPortFilter
$a = $_ | Get-NetFirewallApplicationFilter
[pscustomobject]@{ Rule = $_.DisplayName; Port = $p.LocalPort; Program = $a.Program }
} | Where-Object { $_.Port -in "3389", "5985", "5986", "445" -or $_.Program -match "Users|Temp" }Remote sessions 4
Who is reaching into this host now over file sharing and PowerShell remoting. Remote desktop sign-ins are logon type 10 in the Security log, under Event logs.
Get-SmbShare | Select-Object Name, Path, Description
Get-SmbSession | Select-Object ClientComputerName, ClientUserName, NumOpens
Get-SmbOpenFile | Select-Object ClientComputerName, ClientUserName, PathGet-WSManInstance -ResourceURI shell -Enumerate
Get-WinEvent -FilterHashtable @{ LogName = "Microsoft-Windows-WinRM/Operational" } -MaxEvents 20 |
Select-Object TimeCreated, Id, MessageGet-SmbMapping | Select-Object LocalPath, RemotePath, StatusGet-SmbSession | Where-Object ClientComputerName -eq "10.0.4.17" |
ForEach-Object { Close-SmbSession -SessionId $_.SessionId -Force }Remoting at scale 4
Ask the same question of many hosts at once with Invoke-Command, collect the answers in one place, and do it without leaving reusable credentials behind.
$hosts = Get-Content -Path C:\IR\hosts.txt
Invoke-Command -ComputerName $hosts -ThrottleLimit 32 -ErrorAction SilentlyContinue -ScriptBlock {
Get-CimInstance Win32_Service |
Where-Object { $_.PathName -match "\\Users\\|\\Temp\\" } |
Select-Object Name, PathName
} | Select-Object PSComputerName, Name, PathName |
Export-Csv -Path C:\IR\sweep-services.csv -NoTypeInformation$j = Invoke-Command -ComputerName $hosts -AsJob -ScriptBlock {
Get-ChildItem -Path C:\Users -Recurse -File -Include *.ps1 -ErrorAction SilentlyContinue |
Select-Object FullName, LastWriteTime
}
$j | Wait-Job | Receive-Job | Export-Csv -Path C:\IR\ps1-files.csv -NoTypeInformation$s = New-PSSession -ComputerName ws-fin-042
Invoke-Command -Session $s -ScriptBlock { Get-Process | Select-Object Name, Id, Path }
Invoke-Command -Session $s -ScriptBlock { Get-NetTCPConnection -State Established }
Remove-PSSession -Session $sGet-PSSessionConfiguration | Select-Object Name, PermissionFiles 10
Find what changed on disk, then establish what a file is: its hash, its signature and where it came from.
Get-ChildItem C:\Users -Recurse -Force -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTimeUtc -gt (Get-Date).ToUniversalTime().AddDays(-2) } |
Select-Object FullName, Length, CreationTimeUtc, LastWriteTimeUtcGet-FileHash C:\Users\Public\upd.dll -Algorithm SHA256Get-AuthenticodeSignature C:\Users\Public\upd.dll |
Select-Object Status, SignatureType, @{ n = "Signer"; e = { $_.SignerCertificate.Subject } }Get-Item C:\Users\Public\invoice.zip -Stream * | Select-Object Stream, Length
Get-Content C:\Users\Public\invoice.zip -Stream Zone.IdentifierGet-ChildItem "$env:APPDATA\Microsoft\Windows\Recent" -Filter *.lnk |
Sort-Object LastWriteTime -Descending |
Select-Object -First 30 Name, LastWriteTimeGet-ChildItem C:\Users -Recurse -Force -File -Include *.zip, *.rar, *.7z -ErrorAction SilentlyContinue |
Where-Object Length -gt 10MB |
Select-Object FullName, @{ n = "MB"; e = { [math]::Round($_.Length / 1MB, 1) } }, LastWriteTimeGet-ChildItem C:\Users\Public -Recurse -Force -File -ErrorAction SilentlyContinue |
Get-Item -Stream * |
Where-Object Stream -notin ':$DATA', 'Zone.Identifier' |
Select-Object FileName, Stream, Length$since = (Get-Date).AddDays(-1)
Get-ChildItem -Path C:\Users, C:\ProgramData, C:\Windows\Temp -Recurse -File `
-Include *.exe, *.dll, *.ps1, *.bat, *.vbs, *.js -ErrorAction SilentlyContinue |
Where-Object LastWriteTime -gt $since |
Select-Object FullName, Length, LastWriteTime(Get-Acl -Path "C:\Program Files\VendorApp").Access |
Where-Object { $_.FileSystemRights -match "Write|Modify|FullControl" } |
Select-Object IdentityReference, FileSystemRights, AccessControlTypeGet-ChildItem -Path "C:\`$Recycle.Bin" -Recurse -Force -ErrorAction SilentlyContinue |
Select-Object FullName, Length, LastWriteTimeHashes and signatures at scale 3
Establish what a set of files is, not just one: hash and signature-check a folder, and find what is unsigned or signed by someone unexpected.
Get-ChildItem -Path C:\ProgramData -Recurse -File -Include *.exe, *.dll -ErrorAction SilentlyContinue |
Get-AuthenticodeSignature |
Where-Object Status -ne "Valid" |
Select-Object Path, Status, @{ n = "Signer"; e = { $_.SignerCertificate.Subject } }Get-Process | Where-Object Path | Select-Object -ExpandProperty Path -Unique |
Get-AuthenticodeSignature |
Group-Object { $_.SignerCertificate.Subject } |
Sort-Object Count |
Select-Object Count, NameGet-ChildItem -Path C:\IR\collected -Recurse -File |
Get-FileHash -Algorithm SHA256 |
Select-Object Hash, Path |
Export-Csv -Path C:\IR\collected-hashes.csv -NoTypeInformationThe registry 7
Autostart entries and the traces users leave. HKCU is the hive of the account running PowerShell; another user's is under HKEY_USERS by SID while they are signed in.
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" |
Select-Object -Property * -ExcludeProperty PS*
Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" |
Select-Object -Property * -ExcludeProperty PS*Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\*\* |
Get-ItemProperty | Select-Object FriendlyName, PSChildNameGet-ChildItem "HKCU:\SOFTWARE\Microsoft\Terminal Server Client\Servers" -ErrorAction SilentlyContinue |
Get-ItemProperty | Select-Object PSChildName, UsernameHintGet-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" |
ForEach-Object { Get-ItemProperty $_.PSPath } |
Where-Object Debugger |
Select-Object PSChildName, DebuggerGet-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" |
Select-Object Shell, UserinitGet-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" |
Select-Object "Authentication Packages", "Security Packages", "Notification Packages"Get-ChildItem "HKCU:\Software\Classes\CLSID" -ErrorAction SilentlyContinue |
ForEach-Object { Get-ItemProperty "$($_.PSPath)\InprocServer32" -ErrorAction SilentlyContinue } |
Select-Object PSParentPath, "(default)"Event logs 6
Get-WinEvent with -FilterHashtable asks the log service for only the events you need. Piping a whole log to Where-Object reads every event first. Most of these need an elevated session.
Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4624; StartTime = (Get-Date).AddDays(-1) } |
ForEach-Object {
$d = ([xml]$_.ToXml()).Event.EventData.Data
[pscustomobject]@{
Time = $_.TimeCreated
User = ($d | Where-Object Name -eq "TargetUserName")."#text"
Type = ($d | Where-Object Name -eq "LogonType")."#text"
Source = ($d | Where-Object Name -eq "IpAddress")."#text"
}
}Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4688; StartTime = (Get-Date).AddDays(-1) } |
ForEach-Object {
$d = ([xml]$_.ToXml()).Event.EventData.Data
[pscustomobject]@{
Time = $_.TimeCreated
Process = ($d | Where-Object Name -eq "NewProcessName")."#text"
Parent = ($d | Where-Object Name -eq "ParentProcessName")."#text"
Command = ($d | Where-Object Name -eq "CommandLine")."#text"
}
}Get-WinEvent -FilterHashtable @{ LogName = "System"; Id = 7045 } -MaxEvents 20 |
Select-Object TimeCreated, Message
Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4698 } -MaxEvents 20 |
Select-Object TimeCreated, Message$failed = @(Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4625 } -ErrorAction SilentlyContinue)
$failed.CountGet-WinEvent -ListLog Security, System, "Microsoft-Windows-PowerShell/Operational" |
Select-Object LogName, IsEnabled, RecordCount, MaximumSizeInBytes, LogMode
Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 1102 } -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Message$start = Get-Date "2026-03-14T22:00:00"
$end = $start.AddHours(1)
Get-WinEvent -FilterHashtable @{ LogName = "Security", "System",
"Microsoft-Windows-PowerShell/Operational"; StartTime = $start; EndTime = $end } |
Sort-Object TimeCreated |
Select-Object TimeCreated, LogName, Id, ProviderNameParsing event data into objects 3
Get-WinEvent returns the message as text, but every field is also in the event's XML. Turning that into properties lets you filter, group and export by field.
function ConvertFrom-EventRecord {
param([Parameter(ValueFromPipeline)] $Record)
process {
$x = [xml]$Record.ToXml()
$o = [ordered]@{ Time = $Record.TimeCreated; Id = $Record.Id; Host = $Record.MachineName }
foreach ($d in $x.Event.EventData.Data) { $o[$d.Name] = $d.'#text' }
[pscustomobject]$o
}
}
Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4624 } -MaxEvents 200 |
ConvertFrom-EventRecord |
Select-Object Time, TargetUserName, LogonType, IpAddress$xp = "*[System[EventID=4625]] and *[EventData[Data[@Name='TargetUserName']='administrator']]"
Get-WinEvent -LogName Security -FilterXPath $xp -MaxEvents 100 |
Select-Object TimeCreated, MessageGet-WinEvent -Path C:\IR\Security.evtx -FilterXPath "*[System[(EventID=4624 or EventID=4625)]]" |
Select-Object TimeCreated, Id, Message -First 50PowerShell's own evidence 6
What PowerShell recorded about what it ran. Windows PowerShell 5.1 and PowerShell 7 log to different places; check both.
Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\* |
Select-Object PSChildName, Enable*
Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\PowerShellCore\* -ErrorAction SilentlyContinue |
Select-Object PSChildName, Enable*$log = "Microsoft-Windows-PowerShell/Operational"
Get-WinEvent -FilterHashtable @{ LogName = $log; Id = 4104 } -MaxEvents 50 |
Select-Object TimeCreated, @{ n = "Script"; e = { $_.Properties[2].Value } }
# PowerShell 7 writes the same event to the PowerShellCore/Operational logGet-ChildItem C:\Users\*\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt -Force |
Select-Object FullName, Length, LastWriteTime$b64 = "VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAGgAaQAiAA=="
[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b64))Get-ExecutionPolicy -ListGet-PSReadLineOption | Select-Object HistorySavePath
Get-ChildItem -Path C:\Users\*\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt `
-ErrorAction SilentlyContinue |
Select-Object FullName, Length, LastWriteTimeDecoding obfuscated PowerShell 4
Attackers hide intent with encoding, string building and compression. Undo each layer without running the code.
$b64 = "SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkA"
[System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b64))$bytes = [Convert]::FromBase64String($blob)
$ms = [System.IO.MemoryStream]::new($bytes)
$ds = [System.IO.Compression.DeflateStream]::new($ms, [System.IO.Compression.CompressionMode]::Decompress)
[System.IO.StreamReader]::new($ds).ReadToEnd()$codes = 73, 69, 88
-join ($codes | ForEach-Object { [char]$_ })Get-WinEvent -FilterHashtable @{ LogName = "Microsoft-Windows-PowerShell/Operational"; Id = 4104 } -MaxEvents 50 |
Where-Object { $_.Message -match "Net.WebClient|DownloadString|FromBase64String" } |
Select-Object TimeCreated, MessagePowerShell security state 3
What protects the host from attacker PowerShell, and what does not: execution policy, language mode, logging and the 2.0 engine.
$ExecutionContext.SessionState.LanguageModeGet-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" `
-ErrorAction SilentlyContinue |
Select-Object EnableTranscripting, OutputDirectory, EnableInvocationHeaderStart-Transcript -Path "C:\IR\transcript-$(Get-Date -Format yyyyMMdd-HHmmss).txt"
# ... the investigation ...
Stop-TranscriptPersistence 6
The places a foothold survives a reboot, beyond the Run keys above.
Get-ScheduledTask | Where-Object State -ne "Disabled" |
Select-Object TaskPath, TaskName, Author,
@{ n = "Runs"; e = { ($_.Actions | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join "; " } }Get-ChildItem "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup",
"$env:ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp" -Force |
Select-Object DirectoryName, Name, LastWriteTime
Get-ChildItem C:\Users\*\Documents\*PowerShell\*profile.ps1 -Force -ErrorAction SilentlyContinueGet-CimInstance -Namespace root/subscription -ClassName __EventFilter
Get-CimInstance -Namespace root/subscription -ClassName __EventConsumer
Get-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBindingGet-CimInstance Win32_Service |
Where-Object { $_.PathName -notmatch '^"' -and $_.PathName -match ' ' -and
$_.PathName -notmatch '^C:\\Windows\\' } |
Select-Object Name, StartName, PathNameGet-ScheduledTask | Where-Object State -ne "Disabled" | ForEach-Object {
$i = $_ | Get-ScheduledTaskInfo
[pscustomobject]@{ Task = $_.TaskPath + $_.TaskName; Run = $_.Actions.Execute
Args = $_.Actions.Arguments; LastRun = $i.LastRunTime; Result = $i.LastTaskResult }
}Get-BitsTransfer -AllUsers |
Select-Object DisplayName, JobState, OwnerAccount, TransferType, @{ n = "Files"; e = { $_.FileList.RemoteName } }Microsoft Defender 6
Whether the host's protection was running, what it caught and what it was told to ignore.
Get-MpComputerStatus |
Select-Object AMServiceEnabled, AntivirusEnabled, RealTimeProtectionEnabled,
BehaviorMonitorEnabled, IsTamperProtected, AntivirusSignatureLastUpdatedGet-MpPreference | Select-Object ExclusionPath, ExclusionProcess, ExclusionExtensionGet-MpThreatDetection |
Select-Object ThreatID, InitialDetectionTime, ProcessName, Resources, ActionSuccessGet-WinEvent -FilterHashtable @{
LogName = "Microsoft-Windows-Windows Defender/Operational"; Id = 5001, 5007
} |
Select-Object TimeCreated, Id, MessageGet-MpComputerStatus |
Select-Object AntivirusSignatureLastUpdated, QuickScanEndTime, FullScanEndTime,
RealTimeProtectionEnabled, IsTamperProtectedUpdate-MpSignature
Start-MpScan -ScanType QuickScan
Get-MpThreat | Select-Object ThreatName, SeverityID, IsActive, ResourcesCollect and hunt 2
Save what you read as objects, hash it so it can be trusted later, and ask the same question of other hosts.
$out = "C:\IR\$env:COMPUTERNAME-$(Get-Date -AsUTC -Format "yyyyMMdd'T'HHmm'Z'")"
New-Item -ItemType Directory -Path $out | Out-Null
Get-CimInstance Win32_Process | Export-Clixml "$out\processes.xml"
Get-NetTCPConnection | Export-Clixml "$out\connections.xml"
Get-DnsClientCache | Export-Clixml "$out\dns.xml"
Get-ScheduledTask | Export-Clixml "$out\tasks.xml"
Get-FileHash "$out\*" -Algorithm SHA256 | Export-Csv "$out\hashes.csv" -NoTypeInformation$hash = "PASTE-THE-SHA256-FROM-YOUR-INDICATOR-LIST"
$hosts = Get-Content .\hosts.txt
Invoke-Command -ComputerName $hosts -ErrorVariable failed -ScriptBlock {
Get-ChildItem C:\Users, C:\ProgramData -Recurse -Force -File -Include *.dll, *.exe `
-ErrorAction SilentlyContinue |
Get-FileHash -Algorithm SHA256 | Where-Object Hash -eq $using:hash
}
$failed.CountWorking with output 4
Investigation is mostly shaping results: picking columns, grouping, comparing with a baseline and saving in a form someone else can read.
Get-Process | Select-Object Name, Id,
@{ n = "MB"; e = { [math]::Round($_.WorkingSet64 / 1MB, 1) } },
@{ n = "Started"; e = { $_.StartTime } }Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4625 } -MaxEvents 2000 |
Group-Object { $_.Properties[19].Value } |
Sort-Object Count -Descending |
Select-Object Count, Name -First 10$before = Import-Clixml -Path C:\IR\baseline-services.xml
$now = Get-CimInstance Win32_Service | Select-Object Name, PathName, StartMode
Compare-Object -ReferenceObject $before -DifferenceObject $now -Property Name, PathName, StartMode |
Select-Object Name, PathName, StartMode, SideIndicator$r = Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, Name, CommandLine
$r | Export-Csv -Path C:\IR\processes.csv -NoTypeInformation
$r | ConvertTo-Json -Depth 3 | Out-File -FilePath C:\IR\processes.json -Encoding utf8
$r | Export-Clixml -Path C:\IR\processes.xmlContain 5
Stop an account or a host once the collections are saved. Each of these changes the evidence, so record when you ran it.
Disable-ADAccount -Identity jdoe
Get-ADUser jdoe -Properties Enabled, LockedOut | Select-Object Enabled, LockedOutGet-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction
Test-NetConnection -ComputerName ws-0142 -Port 445 # run from another hostNew-NetFirewallRule -DisplayName "IR allow responder" -Direction Inbound `
-RemoteAddress 10.0.9.5 -Action Allow
New-NetFirewallRule -DisplayName "IR allow responder out" -Direction Outbound `
-RemoteAddress 10.0.9.5 -Action Allow
Set-NetFirewallProfile -All `
-DefaultInboundAction Block -DefaultOutboundAction Block -Enabled TrueDisable-LocalUser -Name "support"
Stop-Service -Name "SuspectSvc" -Force
Set-Service -Name "SuspectSvc" -StartupType Disabled
Disable-ScheduledTask -TaskName "Updater" -TaskPath "\"$f = "C:\Users\Public\update.exe"
$hash = (Get-FileHash -Path $f -Algorithm SHA256).Hash
New-Item -ItemType Directory -Path C:\IR\quarantine -Force | Out-Null
Move-Item -Path $f -Destination "C:\IR\quarantine\$hash.bin"The cloud account 11
The same account in Microsoft Entra ID, through the Microsoft Graph PowerShell SDK. Connect-MgGraph signs you in with the scopes the commands need.
Connect-MgGraph -Scopes "AuditLog.Read.All"
Get-MgAuditLogSignIn -Filter "userPrincipalName eq 'jdoe@contoso.com'" -Top 20 |
Select-Object CreatedDateTime, IpAddress, AppDisplayName, ClientAppUsed,
@{ n = "Error"; e = { $_.Status.ErrorCode } }Connect-MgGraph -Scopes "UserAuthenticationMethod.Read.All"
Get-MgUserAuthenticationMethod -UserId jdoe@contoso.com |
Select-Object Id, @{ n = "Type"; e = { $_.AdditionalProperties["@odata.type"] } }Connect-MgGraph -Scopes "User.ReadWrite.All", "User.RevokeSessions.All"
Update-MgUser -UserId jdoe@contoso.com -AccountEnabled:$false
Revoke-MgUserSignInSession -UserId jdoe@contoso.comConnect-ExchangeOnline
Get-Mailbox -ResultSize Unlimited | ForEach-Object {
$m = $_.UserPrincipalName
Get-InboxRule -Mailbox $m -ErrorAction SilentlyContinue |
Where-Object { $_.ForwardTo -or $_.RedirectTo -or $_.DeleteMessage -or $_.MoveToFolder } |
Select-Object @{ n = "Mailbox"; e = { $m } }, Name, ForwardTo, RedirectTo, MoveToFolder
}Get-AdminAuditLogConfig | Select-Object UnifiedAuditLogIngestionEnabled
Get-Mailbox -ResultSize Unlimited |
Where-Object AuditEnabled -eq $false |
Select-Object UserPrincipalNameGet-TransportRule |
Where-Object { $_.RedirectMessageTo -or $_.BlindCopyTo -or $_.AddToRecipients } |
Select-Object Name, State, RedirectMessageTo, BlindCopyTo, AddToRecipientsConnect-MgGraph -Scopes "AuditLog.Read.All"
Get-MgAuditLogDirectoryAudit -Filter "activityDateTime ge 2026-03-14T00:00:00Z" -Top 200 |
Select-Object ActivityDateTime, ActivityDisplayName, Result,
@{ n = "By"; e = { $_.InitiatedBy.User.UserPrincipalName } }Connect-MgGraph -Scopes "Application.Read.All"
Get-MgApplication -All | ForEach-Object {
$a = $_
$a.PasswordCredentials | Select-Object @{ n = "App"; e = { $a.DisplayName } },
DisplayName, StartDateTime, EndDateTime
}Connect-MgGraph -Scopes "Directory.Read.All"
Get-MgOauth2PermissionGrant -All |
Where-Object ConsentType -eq "AllPrincipals" |
Select-Object ClientId, ScopeConnect-MgGraph -Scopes "IdentityRiskyUser.Read.All"
Get-MgRiskyUser -Filter "riskLevel eq 'high'" |
Select-Object UserPrincipalName, RiskLevel, RiskState, RiskLastUpdatedDateTimeConnect-MgGraph -Scopes "Policy.Read.All"
Get-MgIdentityConditionalAccessPolicy -All |
Select-Object DisplayName, State, ModifiedDateTimeQuick lookup
| Question | Reach for |
|---|---|
| What is this machine, and when did it boot? | Get-CimInstance Win32_OperatingSystem |
| Who is a local administrator? | Get-LocalGroupMember -Group Administrators |
| What is running, from where, started by what? | Get-CimInstance Win32_Process |
| What is it connected to? | Get-NetTCPConnection with OwningProcess |
| Which names did it resolve? | Get-DnsClientCache |
| Who is connected over SMB or WinRM? | Get-SmbSession, Get-WSManInstance |
| What starts automatically? | Run keys, Get-ScheduledTask, Win32_Service, root\subscription |
| Was a file signed, and by whom? | Get-AuthenticodeSignature |
| What is the file? | Get-FileHash, Zone.Identifier stream |
| What did PowerShell run? | Get-WinEvent 4104, PSReadLine history |
| What does this encoded command say? | [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String()) |
| Who is privileged in the domain? | Get-ADGroupMember -Recursive, AdminCount |
| Which accounts can be roasted? | Get-ADUser with ServicePrincipalName or DoesNotRequirePreAuth |
| What changed since the baseline? | Compare-Object against Import-Clixml |
| Ask 200 hosts the same question? | Invoke-Command -ComputerName -ThrottleLimit |
| Is Defender on, and what did it see? | Get-MpComputerStatus, Get-MpThreatDetection |
| Which mailboxes forward mail? | Get-InboxRule, Get-Mailbox ForwardingSmtpAddress |
| End a cloud session? | Revoke-MgUserSignInSession |
| Cut a host off? | Defender isolation, or New-NetFirewallRule and Set-NetFirewallProfile |
From running commands to running the investigation
These collect the evidence. PowerShell for Security Analysts teaches the rest: triaging a host, reading attacker PowerShell, hunting across many hosts, and building the tools that make it repeatable, all on a real intrusion's evidence.
Read the first module free →Weekly security engineering insights
Detection techniques, architecture patterns, and operational judgment, every Tuesday.
No spam. Unsubscribe anytime.