Free Cheatsheet

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.

Windows PowerShell 5.1 and PowerShell 7. Every Windows host has 5.1; PowerShell 7 is installed separately. Get-WmiObject and Get-EventLog do not exist in PowerShell 7. Get-CimInstance and Get-WinEvent, used throughout this page, work in both.
Collect before you change anything. Process lists, connections and the DNS cache change by the minute, and every command you run is itself recorded on the host. Save the volatile collections first, as in Collect and hunt, then investigate.

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.

The whole collection, in order of volatility
$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" -NoTypeInformation
What to read
One folder per host and run, named with the host and time, holding CSV and CLIXML collections, exported logs, a transcript and a hash list stored next to the folder.
What it does not prove
Memory. A memory image needs a dedicated tool, and comes before everything else if the case needs it.

The 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.

What is this machine?
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber, LastBootUpTime Get-CimInstance Win32_ComputerSystem | Select-Object Name, Domain, PartOfDomain, Manufacturer, Model
What to read
The edition and build, the domain the host belongs to, and the last boot. A boot after the activity you are investigating means anything that lived only in memory, such as processes and connections, is gone.
What it does not prove
That the name is unique. Reimaged and renamed machines reuse names; the serial number from Win32_BIOS ties a record to hardware.
How current are its patches?
$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, InstalledOn
What to read
The build and update revision (UBR) give the exact patch level; compare it with Microsoft's update history for that build. Get-HotFix adds the dates updates went in.
What it does not prove
That a given vulnerability is closed. Some fixes need a configuration change or a reboot as well as the update.
Which services run from outside Windows?
Get-CimInstance Win32_Service | Where-Object { $_.PathName -notmatch '^"?C:\\Windows\\' } | Select-Object Name, State, StartMode, StartName, PathName
What to read
Every service whose binary is not under C:\Windows, with the account it runs as. Remote access tools installed as services stand out here, often running as LocalSystem.
What it does not prove
That a service under C:\Windows is benign. An attacker can install a service that runs a system binary with hostile arguments; read the whole PathName.
How is it connected to the network?
Get-NetIPConfiguration | Select-Object InterfaceAlias, IPv4Address, IPv4DefaultGateway, DNSServer
What to read
Each interface with its address, gateway and DNS servers. A DNS server that is not one of yours sends every lookup the host makes to someone else.
What it does not prove
That the configuration was the same during the incident. Addresses from DHCP change; the DHCP server's leases record which host held which address and when.
What time zone, and how long has it been up?
Get-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
What to read
The host's time zone and the uptime. Event logs store UTC; tools that print local time need this to line up with other sources.
What it does not prove
That the clock was right during the incident. Event 4616 records time changes; check it before trusting local times.
What software is installed, and when?
$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 30
What to read
Programs registered for uninstall, newest first. Remote access tools, archivers and sync clients installed during the incident window are the ones to ask about.
What it does not prove
That nothing else was installed. Portable tools copied to disk never register here; the file and process sections catch those.
Which Windows optional features are on, including PowerShell 2.0?
Get-WindowsOptionalFeature -Online | Where-Object State -eq "Enabled" | Select-Object FeatureName
What to read
Enabled features. MicrosoftWindowsPowerShellV2Root enabled means an attacker can start the 2.0 engine, which has no script block logging (see PowerShell security state).
What it does not prove
That 2.0 was used. Event 400 in the Windows PowerShell log records the engine version each time it starts.

Accounts 5

Who can sign in to the host and who controls it, then the events that record changes to either.

Who is in the local Administrators group?
Get-LocalGroupMember -Group Administrators | Select-Object Name, ObjectClass, PrincipalSource
What to read
Each member and where it comes from: Local for an account on this machine, ActiveDirectory for a domain account or group. Compare against the members every host in the fleet should have.
What it does not prove
Whether an extra member was approved. Membership is a fact; whether it was sanctioned is a question for the host's owner.
Which local accounts are enabled?
Get-LocalUser | Where-Object Enabled | Select-Object Name, PasswordLastSet, LastLogon, Description
What to read
Enabled local accounts and when their passwords were set. A password set inside the window you are investigating points to an account created or taken over then.
What it does not prove
Who created the account. The Security log's account events, below, name the account that made the change.
When were accounts created, enabled, reset or added to a group?
Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4720, 4722, 4724, 4738, 4732 } | Select-Object TimeCreated, Id, Message
What to read
4720 created, 4722 enabled, 4724 password reset, 4738 changed, 4732 added to a security-enabled local group. A run of them within seconds is one actor setting up an account.
What it does not prove
That nothing happened if the query returns nothing. Check how far back the Security log reaches with Get-WinEvent -ListLog Security before reading an absence.
Which local groups exist, and who is in the ones that grant remote access?
Get-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 }
What to read
Members of the groups that allow RDP and WinRM, with whether each is local or from the domain.
What it does not prove
Who actually connected. The logon events (4624 Type 10 and Type 3) record that.
Which local accounts have never had a password set, or never expire?
Get-LocalUser | Select-Object Name, Enabled, PasswordRequired, PasswordExpires, PasswordLastSet, LastLogon | Sort-Object LastLogon -Descending
What to read
Enabled accounts with no password required, or a password last set long ago, are the weak ones.
What it does not prove
That an account is unused. LastLogon is local to this host.

The 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.

Which domain controllers serve the domain?
Get-ADDomainController -Filter * | Select-Object Name, IPv4Address, Site, OperatingSystem, IsGlobalCatalog
What to read
Every domain controller with its site and operating system. These are the hosts whose Security logs record domain sign-ins and Kerberos tickets, so they are where account questions get answered.
What it does not prove
That the list is the set of machines acting as domain controllers. A rogue replication partner, as in a DCShadow attack, is registered only for as long as the attack runs.
Which enabled accounts set a password recently, or have not signed in for months?
Get-ADUser -Filter "Enabled -eq 'True'" -Properties LastLogonDate, PasswordLastSet | Sort-Object PasswordLastSet -Descending | Select-Object SamAccountName, PasswordLastSet, LastLogonDate
What to read
Passwords set inside the incident window come to the top. An enabled account with an old LastLogonDate is one nobody would notice being used.
What it does not prove
The last sign-in to the day. LastLogonDate comes from lastLogonTimestamp, which replicates only when it is days out of date, so it can lag by up to two weeks.
Which user accounts can be Kerberoasted?
Get-ADUser -LDAPFilter "(servicePrincipalName=*)" -Properties ServicePrincipalName, PasswordLastSet | Select-Object SamAccountName, Enabled, PasswordLastSet, ServicePrincipalName
What to read
User accounts with a service principal name. Any domain user can request a service ticket for them, encrypted with a key derived from the account's password, and crack it offline. An old password on one of these is the risk.
What it does not prove
That it was attacked. Event 4769 on the domain controllers records each service ticket request; a burst of them from one account, with RC4 encryption (0x17), is the pattern.
Which accounts do not require Kerberos pre-authentication?
Get-ADUser -Filter "DoesNotRequirePreAuth -eq 'True'" -Properties DoesNotRequirePreAuth | Select-Object SamAccountName, Enabled
What to read
Accounts open to AS-REP roasting: anyone can request a ticket for them and crack it offline.
What it does not prove
That they were roasted. Event 4768 with Pre-Authentication Type 0 on a domain controller records requests.
Which accounts are or were privileged?
Get-ADUser -Filter "AdminCount -eq 1" -Properties AdminCount, LastLogonDate | Select-Object SamAccountName, Enabled, LastLogonDate
What to read
Accounts protected by AdminSDHolder, which includes anyone who was ever in a protected group, because AdminCount is not cleared when they leave.
What it does not prove
Current membership. Read the groups themselves with Get-ADGroupMember.
Who is in the privileged groups now?
"Domain Admins", "Enterprise Admins", "Schema Admins", "Administrators" | ForEach-Object { $g = $_ Get-ADGroupMember -Identity $g -Recursive | Select-Object @{ n = "Group"; e = { $g } }, SamAccountName, ObjectClass }
What to read
Effective members of each group, nested groups expanded. Save it: it is the baseline to compare after eviction.
What it does not prove
When anyone was added. Events 4728, 4732 and 4756 on domain controllers record additions.
Which computers and accounts are trusted for delegation?
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
What to read
Unconstrained delegation outside the domain controllers, and constrained delegation targets. A compromised host with unconstrained delegation holds tickets of everyone who authenticates to it.
What it does not prove
That delegation was abused. Look for 4769 requests for the delegated services.
Who can change AdminSDHolder?
$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, AccessControlType
What to read
Every principal with full control or the right to change permissions on AdminSDHolder. Whatever is here is copied to every protected account each hour.
What it does not prove
When an entry was added. Directory change auditing (5136) records it, if a SACL is set.
What is the password and lockout policy?
Get-ADDefaultDomainPasswordPolicy | Select-Object MinPasswordLength, LockoutThreshold, LockoutDuration, MaxPasswordAge
What to read
The lockout threshold sets how many guesses a spray can make per account; zero means no lockout at all.
What it does not prove
Fine-grained policies, which can apply different rules to groups.
Which domains does this one trust?
Get-ADTrust -Filter * | Select-Object Name, Direction, TrustType, SIDFilteringQuarantined
What to read
Every trust and its direction. SID filtering off on an external trust makes SID History attacks across it work.
What it does not prove
That a trust is in use. Logons across it show in the trusting side's Security log.
Is replication healthy?
$domain = (Get-ADDomain).DNSRoot Get-ADReplicationPartnerMetadata -Target $domain -Scope Domain | Select-Object Server, Partner, LastReplicationSuccess, LastReplicationResult
What to read
Each domain controller's last successful replication. Check this before a krbtgt reset.
What it does not prove
That nothing replicated that should not have. DCSync uses the same replication protocol; event 4662 records it.

Credentials on the host 3

What an intruder with administrative rights could take from this machine's memory, and the Kerberos tickets it holds now.

Can credentials be read from memory?
Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" ` -Name UseLogonCredential -ErrorAction SilentlyContinue Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" | Select-Object RunAsPPL, LmCompatibilityLevel
What to read
UseLogonCredential set to 1 makes WDigest keep sign-in passwords in memory in clear text; an intruder sets it and waits for the next sign-in. RunAsPPL 1 or 2 means LSA protection is configured: 1 with a UEFI lock, 2 without one, enforced only on Windows 11 22H2 and later.
What it does not prove
That credentials were or were not taken. These are settings; a dump of LSASS shows as process access in Sysmon or in Defender for Endpoint, not here.
Which Kerberos tickets and logon sessions does the host hold?
klist klist sessions
What to read
klist lists the tickets of the current logon session, including the service each one is for; klist sessions lists every logon session on the host with its logon ID and authentication package. An account in that list that has no reason to be on this host is a lead.
What it does not prove
Whose tickets these are. Without parameters klist shows only your own; run it elevated with -li and a session's logon ID (0x3e7 is SYSTEM) to read another session.
Is LSA protection on, and is Credential Guard running?
Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" | Select-Object RunAsPPL, LsaCfgFlags Get-CimInstance -Namespace root\Microsoft\Windows\DeviceGuard ` -ClassName Win32_DeviceGuard | Select-Object SecurityServicesRunning
What to read
RunAsPPL 1 or 2 means LSASS runs as a protected process; SecurityServicesRunning containing 1 means Credential Guard is running.
What it does not prove
That credentials are safe. Protection makes dumping LSASS harder; it does nothing for credentials typed into a phishing page.

Processes and connections 8

What is running, what started it, and what it is talking to. Collect these first: they change while you work.

What is running, and what started it?
Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, Name, ExecutablePath, CommandLine
What to read
The command line and parent of every process. Get-Process has neither the parent nor, in Windows PowerShell 5.1, the command line; Win32_Process has both. Read the chain: an Office application or a browser starting a shell is the pattern to chase.
What it does not prove
That ParentProcessId is still the parent. When a parent exits, Windows can reuse its ID; check that the parent's creation time is earlier than the child's.
Who owns a process?
Get-CimInstance Win32_Process -Filter "Name = 'rundll32.exe'" | Invoke-CimMethod -MethodName GetOwner | Select-Object Domain, User
What to read
The account each instance runs as. The same binary running as a user and as SYSTEM are two different findings.
What it does not prove
How it got those rights. A SYSTEM process may have been started by a service or a task; find what launched it.
What is each process connected to?
Get-NetTCPConnection -State Established, Listen | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess, @{ n = "Process"; e = { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name } }
What to read
Each connection with the process that owns it. Join OwningProcess to the process list above for its command line and parent.
What it does not prove
What was sent. A connection is a fact about now; it says nothing about how much data crossed it or what it was.
Which names has the host resolved recently?
Get-DnsClientCache | Select-Object Entry, Type, TimeToLive, Data
What to read
The names behind the remote addresses: a connection to an address resolved from a remote access relay or a new domain reads differently from the bare IP.
What it does not prove
That a name was never resolved. Entries leave the cache when their time to live runs out, so the cache holds only the recent past.
Which processes run from user-writable folders?
Get-Process | Where-Object { $_.Path -match "\\AppData\\|\\Temp\\|\\Users\\Public\\|\\ProgramData\\" } | Select-Object Id, ProcessName, Path, StartTime
What to read
Processes whose image is in a folder any user can write to. Legitimate software lives here too (updaters, some browsers), so read the names.
What it does not prove
That a process in Program Files is benign. Sign-check it in Hashes and signatures.
What is the full process tree with command lines?
Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate | Sort-Object CreationDate
What to read
Every process with its parent ID and command line, in start order. A parent ID that no longer exists means the parent has exited.
What it does not prove
The account each runs as. Invoke-CimMethod with GetOwner, in Processes and connections, adds it.
How do I stop a process and everything it started?
$root = 4242 $kids = Get-CimInstance Win32_Process -Filter "ParentProcessId = $root" $kids | ForEach-Object { Stop-Process -Id $_.ProcessId -Force } Stop-Process -Id $root -Force
What to read
The children are stopped first so none are left orphaned and running.
What it does not prove
That it will not restart. Remove its persistence first, or it comes back at the next trigger.
Which UDP ports are open, and by what?
Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess, @{ n = "Process"; e = { (Get-Process -Id $_.OwningProcess).ProcessName } }
What to read
Listening UDP endpoints with the owning process.
What it does not prove
Traffic. UDP has no connection state to read.

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.

Which DNS servers does each interface use?
Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object InterfaceAlias, ServerAddresses
What to read
The resolvers per interface. A resolver outside your estate sends every lookup to someone else.
What it does not prove
That DHCP set them. A change by script or by policy looks the same here.
Is the hosts file redirecting names?
Get-Content -Path C:\Windows\System32\drivers\etc\hosts | Where-Object { $_ -notmatch "^\s*#" -and $_.Trim() }
What to read
Every active hosts entry. Entries for security vendors' update servers or for your own sign-in pages are tampering.
What it does not prove
Resolution from DNS, which the DNS cache shows.
Which neighbors and routes does the host have?
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, InterfaceAlias
What to read
The ARP cache shows the hosts this one talked to recently on its own subnet; routes show any path added by hand.
What it does not prove
Traffic beyond the local subnet. The neighbor cache only holds the local link.
Is a proxy set for the system or the user?
netsh winhttp show proxy Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" | Select-Object ProxyEnable, ProxyServer, AutoConfigURL
What to read
WinHTTP proxy (used by services) and the user's proxy and PAC file. A proxy the user did not set can read their traffic.
What it does not prove
Proxy settings in individual applications.
Which firewall rules allow inbound traffic, and to what?
Get-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" }
What to read
Inbound allow rules for the remote access ports, and rules for programs in user folders.
What it does not prove
Whether traffic used them. The firewall log, if enabled, records allowed connections.

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.

Who has files open over SMB?
Get-SmbShare | Select-Object Name, Path, Description Get-SmbSession | Select-Object ClientComputerName, ClientUserName, NumOpens Get-SmbOpenFile | Select-Object ClientComputerName, ClientUserName, Path
What to read
The shares this host offers, the clients connected to it and the files they have open. An administrative share such as C$ or ADMIN$ opened from a workstation is how tools are copied in for remote execution.
What it does not prove
Past access. These are open sessions only; Security event 5140 records share access when that auditing is enabled.
Is anyone connected over PowerShell remoting?
Get-WSManInstance -ResourceURI shell -Enumerate Get-WinEvent -FilterHashtable @{ LogName = "Microsoft-Windows-WinRM/Operational" } -MaxEvents 20 | Select-Object TimeCreated, Id, Message
What to read
Open remote shells with their owner and client address, then recent WinRM activity. The process a remote session runs in is wsmprovhost.exe; its children are what the remote user ran.
What it does not prove
Who connected in the past. The WinRM log is small and rolls over quickly; logon type 3 events in the Security log from the same address cover a longer period.
Which drives does the user have mapped, and to where?
Get-SmbMapping | Select-Object LocalPath, RemotePath, Status
What to read
Network drives mapped in this session: a quick view of the file servers the user reaches.
What it does not prove
Other users' mappings. Each user's mappings live in their own session and their HKCU\Network key.
How do I end an SMB session from an attacker's host?
Get-SmbSession | Where-Object ClientComputerName -eq "10.0.4.17" | ForEach-Object { Close-SmbSession -SessionId $_.SessionId -Force }
What to read
Every session from that address is closed.
What it does not prove
That it stays closed. The client can reconnect; block the address too.

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.

How do I run a check on many hosts?
$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
What to read
Results from every host that answered, tagged with PSComputerName. ThrottleLimit caps how many run at once.
What it does not prove
Hosts that did not answer. Compare the host list with the PSComputerName values.
How do I run a long collection as a background job?
$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
What to read
The command returns at once; the results are collected when the job finishes.
What it does not prove
That every host finished. Check each child job's State for Failed.
How do I keep a session open for several commands?
$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 $s
What to read
One connection reused, which is faster and leaves one logon on the target instead of one per command.
What it does not prove
Anything on its own; it carries the other checks.
Which remoting endpoints does a host offer?
Get-PSSessionConfiguration | Select-Object Name, Permission
What to read
The endpoints and who may connect. A custom endpoint with broad permissions is a way in.
What it does not prove
Who has connected. The WinRM Operational log and logon events record that.

Files 10

Find what changed on disk, then establish what a file is: its hash, its signature and where it came from.

What changed in user folders in the last two days?
Get-ChildItem C:\Users -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTimeUtc -gt (Get-Date).ToUniversalTime().AddDays(-2) } | Select-Object FullName, Length, CreationTimeUtc, LastWriteTimeUtc
What to read
Files written in the window, including hidden ones (-Force). Executables, scripts and archives in Downloads, AppData and Temp come first.
What it does not prove
When a file arrived. Timestamps can be set by any program that writes the file, including an intruder's.
What is the file's hash?
Get-FileHash C:\Users\Public\upd.dll -Algorithm SHA256
What to read
SHA256 by default, which is what you record for integrity. Compute MD5 or SHA1 only to match an indicator list that uses them.
What it does not prove
That the file is malicious or clean. An unknown hash is unknown, not safe.
Is it signed, and by whom?
Get-AuthenticodeSignature C:\Users\Public\upd.dll | Select-Object Status, SignatureType, @{ n = "Signer"; e = { $_.SignerCertificate.Subject } }
What to read
Status Valid with a known signer, or NotSigned. Catalog-signed Windows binaries show SignatureType Catalog.
What it does not prove
That a signed file is safe. Signed remote access and administration tools are common in intrusions; the signer tells you what it is, not why it is there.
Where did a download come from?
Get-Item C:\Users\Public\invoice.zip -Stream * | Select-Object Stream, Length Get-Content C:\Users\Public\invoice.zip -Stream Zone.Identifier
What to read
A Zone.Identifier stream is the mark of the web. ZoneId=3 means the Internet zone, and browsers usually add HostUrl and ReferrerUrl, the address it was downloaded from.
What it does not prove
That a file without the stream was not downloaded. Copies, some archive tools and some download methods do not write it.
What did the user open recently?
Get-ChildItem "$env:APPDATA\Microsoft\Windows\Recent" -Filter *.lnk | Sort-Object LastWriteTime -Descending | Select-Object -First 30 Name, LastWriteTime
What to read
One shortcut per file or folder the user opened, newest first. A shortcut to a file on a share, a removable drive or in Downloads places the user and the file together.
What it does not prove
That the file still exists or what it held. The shortcut records the path at the time; for another user, read the same folder under their profile.
Which large archives sit in user folders?
Get-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) } }, LastWriteTime
What to read
Archives over 10 MB with their size and time. A large archive created shortly before outbound traffic to a file sharing service is the staging pattern.
What it does not prove
That anything left the host. Compare its time and size with network or proxy records before calling it exfiltration.
Which files carry hidden streams?
Get-ChildItem C:\Users\Public -Recurse -Force -File -ErrorAction SilentlyContinue | Get-Item -Stream * | Where-Object Stream -notin ':$DATA', 'Zone.Identifier' | Select-Object FileName, Stream, Length
What to read
Every alternate data stream other than the file's content and the mark of the web. The single quotes matter: in double quotes PowerShell reads $DATA as a variable and the filter matches every stream.
What it does not prove
That a stream is hostile. Some applications store metadata this way; read the stream with Get-Content -Stream.
Which executables were written anywhere in the last day?
$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
What to read
New scripts and binaries in the folders attackers use most.
What it does not prove
That a file with an old timestamp is old. Timestamps can be set; the $MFT and the USN journal are harder to fake.
Who can write to this folder?
(Get-Acl -Path "C:\Program Files\VendorApp").Access | Where-Object { $_.FileSystemRights -match "Write|Modify|FullControl" } | Select-Object IdentityReference, FileSystemRights, AccessControlType
What to read
Write access for Users, Authenticated Users or Everyone on a folder a service runs from is a privilege escalation path: replace the binary, wait for the service to start.
What it does not prove
That it was used. Compare the binary's hash with the vendor's.
What is in the Recycle Bin?
Get-ChildItem -Path "C:\`$Recycle.Bin" -Recurse -Force -ErrorAction SilentlyContinue | Select-Object FullName, Length, LastWriteTime
What to read
Each user's deleted items, under a folder named for their SID. $I files hold the original path and deletion time.
What it does not prove
Files deleted with Shift+Delete or by tools, which skip the Recycle Bin.

Hashes 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.

Which executables in a folder are unsigned?
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 } }
What to read
Files with no signature, an invalid one or a revoked one, under a folder attackers use.
What it does not prove
That a validly signed file is safe. Stolen and abused certificates sign malware; read the signer.
Who signed the binaries that are running?
Get-Process | Where-Object Path | Select-Object -ExpandProperty Path -Unique | Get-AuthenticodeSignature | Group-Object { $_.SignerCertificate.Subject } | Sort-Object Count | Select-Object Count, Name
What to read
Running images grouped by signer, rarest first. A signer that appears once is the one to read.
What it does not prove
Catalog-signed system files show a status from the catalog, not an embedded signature; that is normal.
How do I hash a folder and keep the list?
Get-ChildItem -Path C:\IR\collected -Recurse -File | Get-FileHash -Algorithm SHA256 | Select-Object Hash, Path | Export-Csv -Path C:\IR\collected-hashes.csv -NoTypeInformation
What to read
A SHA-256 for every file collected, saved alongside them for chain of custody.
What it does not prove
That the files were unchanged before you collected them.

The 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.

What starts at sign-in from the Run keys?
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*
What to read
One property per autostart entry. A command line that runs rundll32, a script host or PowerShell from a user-writable folder is the entry to explain.
What it does not prove
Every autostart location. Services, tasks, startup folders, profiles and WMI subscriptions are separate; see Persistence below.
Which USB storage devices have been connected?
Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\*\* | Get-ItemProperty | Select-Object FriendlyName, PSChildName
What to read
Each device by name, and its serial number as the key name (PSChildName). The same serial on two hosts is one device.
What it does not prove
When it was connected or what was copied. Event 6416 in the Security log, where enabled, records when a device was recognized.
Which hosts has this user connected to over RDP?
Get-ChildItem "HKCU:\SOFTWARE\Microsoft\Terminal Server Client\Servers" -ErrorAction SilentlyContinue | Get-ItemProperty | Select-Object PSChildName, UsernameHint
What to read
The outbound side of remote desktop: each server this user has connected to, with the account name used. A chain of these across hosts is a path of lateral movement.
What it does not prove
Inbound sessions to this host. Those are in the Security log as logon type 10, below.
Which Image File Execution Options debuggers are set?
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" | ForEach-Object { Get-ItemProperty $_.PSPath } | Where-Object Debugger | Select-Object PSChildName, Debugger
What to read
A Debugger value makes Windows start that program instead of the named one. On sethc.exe or utilman.exe it gives a SYSTEM shell at the sign-in screen.
What it does not prove
That nothing else hijacks execution. GlobalFlag with SilentProcessExit is a related technique.
What runs at sign-in through Winlogon?
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" | Select-Object Shell, Userinit
What to read
Shell should be explorer.exe and Userinit should be C:\Windows\system32\userinit.exe, followed by a comma. Anything appended runs at every sign-in.
What it does not prove
Per-user overrides, which live under HKCU with the same names.
Which LSA packages load into LSASS?
Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" | Select-Object "Authentication Packages", "Security Packages", "Notification Packages"
What to read
DLLs LSASS loads at boot. An unfamiliar name here sees every password as it is set or used.
What it does not prove
That a listed DLL is the real one. Hash it and check its signature.
Which COM objects are registered per user?
Get-ChildItem "HKCU:\Software\Classes\CLSID" -ErrorAction SilentlyContinue | ForEach-Object { Get-ItemProperty "$($_.PSPath)\InprocServer32" -ErrorAction SilentlyContinue } | Select-Object PSParentPath, "(default)"
What to read
Per-user COM registrations override the machine-wide ones, so a DLL here is loaded by anything that creates that object: COM hijacking.
What it does not prove
That a registration is malicious. Some software registers per user legitimately; check the DLL path.

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.

Who signed in, how, and from where?
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" } }
What to read
Each logon with its type: 2 at the keyboard, 3 over the network, 10 over remote desktop. Type 10 from an address that is not an administrator's workstation is the first lead for lateral movement.
What it does not prove
What the session did. Join it to process creation, below, through the logon ID.
Which processes started, with their command lines?
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" } }
What to read
The process history the live process list cannot give you: processes that have already exited, with their parents.
What it does not prove
Anything, if process creation auditing is off. Command lines appear only when the command-line policy is also enabled; an empty Command field means it was not.
Were services installed or tasks created?
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
What to read
System 7045 records a service installed, with its binary path; Security 4698 records a scheduled task created, with its full XML. Both double as the cleanup list.
What it does not prove
That none exist if none are logged. 4698 needs task auditing enabled; check the tasks and services themselves too.
How do I tell no events from an error?
$failed = @(Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4625 } -ErrorAction SilentlyContinue) $failed.Count
What to read
A count. When nothing matches, Get-WinEvent writes an error rather than returning nothing; wrapping it in @() and silencing that error turns "none found" into 0.
What it does not prove
That the error you silenced was the "none found" one. Run it once without -ErrorAction to see access denied or a misspelled log name.
Has a log been cleared, or is it too small to hold the incident?
Get-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
What to read
Whether each log is on and how much it can hold, then Security event 1102, written when the Security log is cleared, with the account that cleared it. System event 104 records the other logs being cleared.
What it does not prove
That nothing was suppressed. An intruder can stop the logging service or disable auditing without clearing anything; a gap in the record times is the sign.
What happened in a one-hour window, across logs?
$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, ProviderName
What to read
One timeline from three logs for the window around an alert.
What it does not prove
Events in logs you did not name.

Parsing 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.

How do I get an event's fields as properties?
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
What to read
One object per event with a property for every EventData field, named as in the schema (TargetUserName, LogonType, IpAddress).
What it does not prove
Fields in UserData rather than EventData, which some providers use; read $x.Event.UserData instead.
When is XPath better than a hashtable?
$xp = "*[System[EventID=4625]] and *[EventData[Data[@Name='TargetUserName']='administrator']]" Get-WinEvent -LogName Security -FilterXPath $xp -MaxEvents 100 | Select-Object TimeCreated, Message
What to read
XPath filters on EventData fields inside the log service, which a hashtable cannot do except through its Data key.
What it does not prove
Complex logic: XPath in the event log supports only a subset of XPath 1.0.
How do I read an exported .evtx file?
Get-WinEvent -Path C:\IR\Security.evtx -FilterXPath "*[System[(EventID=4624 or EventID=4625)]]" | Select-Object TimeCreated, Id, Message -First 50
What to read
Events from a saved log, with the same filters as a live one.
What it does not prove
Messages for providers not installed on your analysis machine; the fields are still in the XML.

PowerShell's own evidence 6

What PowerShell recorded about what it ran. Windows PowerShell 5.1 and PowerShell 7 log to different places; check both.

Is PowerShell logging turned on?
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*
What to read
Which of script block, module and transcription logging the policy enables: the first key for Windows PowerShell 5.1, the second for PowerShell 7.
What it does not prove
That the logs are complete. Logs roll over at their size limit, and a policy enabled after the activity recorded nothing before it.
What script blocks did PowerShell run?
$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 log
What to read
Event 4104 holds the text PowerShell actually compiled, after any decoding the attacker did, so an encoded command appears here in clear.
What it does not prove
The whole script, in one event. Long scripts are split across several 4104 events; reassemble them by ScriptBlockId.
What did users type at the console?
Get-ChildItem C:\Users\*\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt -Force | Select-Object FullName, Length, LastWriteTime
What to read
One history file per user who has used the console, holding the commands they typed, oldest first.
What it does not prove
Commands that were not typed. Scripts and -EncodedCommand runs never reach the history, and a user can turn saving off with Set-PSReadLineOption -HistorySaveStyle SaveNothing.
What does an encoded command say?
$b64 = "VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAGgAaQAiAA==" [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b64))
What to read
The command PowerShell would have run: -EncodedCommand takes Base64 of UTF-16LE text, so decode it as Unicode. This decodes; it runs nothing.
What it does not prove
What the decoded text then did. A cradle that downloads a second stage needs that stage, from the script block log or the network.
What is the execution policy, and does it matter?
Get-ExecutionPolicy -List
What to read
The policy at each scope, with MachinePolicy and UserPolicy set by Group Policy. It tells you whether double-clicked scripts would run.
What it does not prove
Protection. The execution policy is not a security boundary: -ExecutionPolicy Bypass on a command line overrides it for that process, so look for it in process command lines.
Where is each user's PSReadLine history?
Get-PSReadLineOption | Select-Object HistorySavePath Get-ChildItem -Path C:\Users\*\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt ` -ErrorAction SilentlyContinue | Select-Object FullName, Length, LastWriteTime
What to read
The history file for each user who used the console; it survives restarts.
What it does not prove
Commands run in scripts, through remoting or by the ISE, which do not write to it.

Decoding obfuscated PowerShell 4

Attackers hide intent with encoding, string building and compression. Undo each layer without running the code.

How do I decode an -EncodedCommand value?
$b64 = "SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkA" [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b64))
What to read
-EncodedCommand takes Base64 of UTF-16LE text, so decode with Unicode, not UTF8. This one reads IEX (New-Object Net.WebClient).
What it does not prove
What the next stage downloads. Decode that separately; never pipe it to Invoke-Expression.
How do I decompress a Deflate or GZip blob?
$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()
What to read
The decompressed script text. Swap DeflateStream for GZipStream when the blob starts with 1F 8B.
What it does not prove
That this is the last layer. Payloads are often encoded several times.
How do I rebuild a string made from character codes?
$codes = 73, 69, 88 -join ($codes | ForEach-Object { [char]$_ })
What to read
The characters joined back into text, here IEX.
What it does not prove
That the code is harmless. Read it; do not run it.
Where do I find the deobfuscated text without decoding anything?
Get-WinEvent -FilterHashtable @{ LogName = "Microsoft-Windows-PowerShell/Operational"; Id = 4104 } -MaxEvents 50 | Where-Object { $_.Message -match "Net.WebClient|DownloadString|FromBase64String" } | Select-Object TimeCreated, Message
What to read
Script block logging records the code PowerShell compiled, after the encoded command was decoded. Often the answer is already in 4104.
What it does not prove
Code that never reached PowerShell, such as a payload run by mshta or rundll32.

PowerShell security state 3

What protects the host from attacker PowerShell, and what does not: execution policy, language mode, logging and the 2.0 engine.

What language mode is this session in?
$ExecutionContext.SessionState.LanguageMode
What to read
FullLanguage, or ConstrainedLanguage where App Control or AppLocker enforce it. Constrained Language blocks most of the .NET calls attack tools rely on.
What it does not prove
Other sessions: each runspace has its own mode.
Is transcription on, and where does it write?
Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" ` -ErrorAction SilentlyContinue | Select-Object EnableTranscripting, OutputDirectory, EnableInvocationHeader
What to read
Whether every session writes a transcript, and to which folder. Transcripts hold the output as well as the commands.
What it does not prove
That transcripts are complete: a session can be started with policies bypassed by an administrator.
How do I record my own session?
Start-Transcript -Path "C:\IR\transcript-$(Get-Date -Format yyyyMMdd-HHmmss).txt" # ... the investigation ... Stop-Transcript
What to read
Every command you ran and its output, for the case file.
What it does not prove
Actions taken outside the session, such as in a graphical tool.

Persistence 6

The places a foothold survives a reboot, beyond the Run keys above.

Which scheduled tasks run, and what do they run?
Get-ScheduledTask | Where-Object State -ne "Disabled" | Select-Object TaskPath, TaskName, Author, @{ n = "Runs"; e = { ($_.Actions | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join "; " } }
What to read
Every enabled task with its command. Tasks outside \Microsoft\ come first, then anything running PowerShell, rundll32 or a script host.
What it does not prove
That a task under \Microsoft\ or with a Microsoft author is Microsoft's. The path and the Author field are set by whoever creates the task.
What is in the startup folders and PowerShell profiles?
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 SilentlyContinue
What to read
Anything besides desktop.ini in a startup folder runs at sign-in. A profile runs every time that user starts PowerShell.
What it does not prove
The all-users profiles. Those sit beside the PowerShell executable ($PSHOME) for each version; check both.
Are there WMI event subscriptions?
Get-CimInstance -Namespace root/subscription -ClassName __EventFilter Get-CimInstance -Namespace root/subscription -ClassName __EventConsumer Get-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding
What to read
A filter (the trigger), a consumer (the action) and a binding joining them. A CommandLineEventConsumer or ActiveScriptEventConsumer bound to a filter is the persistence pattern.
What it does not prove
That every subscription is hostile. Windows and management agents create their own; the consumer's command is what to read.
Which services use an unquoted path with spaces?
Get-CimInstance Win32_Service | Where-Object { $_.PathName -notmatch '^"' -and $_.PathName -match ' ' -and $_.PathName -notmatch '^C:\\Windows\\' } | Select-Object Name, StartName, PathName
What to read
An unquoted path such as C:\Program Files\Vendor App\svc.exe lets a file at C:\Program.exe run first, as the service account.
What it does not prove
That it is exploitable. The attacker also needs write access to an earlier folder in the path.
What does each scheduled task run, and when did it last run?
Get-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 } }
What to read
Each enabled task with its action and last run. Tasks that ran during the incident window are the ones to read.
What it does not prove
Who created a task. Event 4698 and the Task Scheduler Operational log record that.
What is BITS transferring?
Get-BitsTransfer -AllUsers | Select-Object DisplayName, JobState, OwnerAccount, TransferType, @{ n = "Files"; e = { $_.FileList.RemoteName } }
What to read
Background transfers with their remote URLs. BITS jobs survive reboots and are used to download payloads.
What it does not prove
Completed and removed jobs. The Bits-Client Operational log keeps their history.

Microsoft Defender 6

Whether the host's protection was running, what it caught and what it was told to ignore.

Is protection on?
Get-MpComputerStatus | Select-Object AMServiceEnabled, AntivirusEnabled, RealTimeProtectionEnabled, BehaviorMonitorEnabled, IsTamperProtected, AntivirusSignatureLastUpdated
What to read
Each protection component and the age of the signatures. Real-time protection off, or signatures days old on a connected host, is a finding.
What it does not prove
That it was on during the incident. This is the state now; the Defender operational log records changes.
What has it been told to ignore?
Get-MpPreference | Select-Object ExclusionPath, ExclusionProcess, ExclusionExtension
What to read
Every exclusion by path, process and extension. A user-writable folder or a remote access tool in these lists is a reason to ask who added it.
What it does not prove
Who added it or when. Defender writes event 5007 to its operational log when its configuration changes.
What has it detected, and did it act?
Get-MpThreatDetection | Select-Object ThreatID, InitialDetectionTime, ProcessName, Resources, ActionSuccess
What to read
Each detection with the file or process involved and whether remediation succeeded. ActionSuccess False means the threat may still be present.
What it does not prove
That nothing ran because nothing was detected. A tool Defender does not recognize, or one in an excluded path, leaves no detection.
Was protection turned off or reconfigured?
Get-WinEvent -FilterHashtable @{ LogName = "Microsoft-Windows-Windows Defender/Operational"; Id = 5001, 5007 } | Select-Object TimeCreated, Id, Message
What to read
5001 records real-time protection being disabled; 5007 records any configuration change, with the old and new values.
What it does not prove
Who made the change. The event names the setting, not the account; correlate its time with logons and process creation.
Are the signatures current, and when was the last scan?
Get-MpComputerStatus | Select-Object AntivirusSignatureLastUpdated, QuickScanEndTime, FullScanEndTime, RealTimeProtectionEnabled, IsTamperProtected
What to read
Signature age and scan times. Signatures days old on a connected host suggest updates are being blocked.
What it does not prove
That a scan would find the threat. Signatures catch known files, not behavior.
How do I update and scan now?
Update-MpSignature Start-MpScan -ScanType QuickScan Get-MpThreat | Select-Object ThreatName, SeverityID, IsActive, Resources
What to read
Fresh signatures, a quick scan, and the threats known on the host.
What it does not prove
That the host is clean. Run it after collection, because remediation removes files you may need.

Collect 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.

How do I save a snapshot I can trust later?
$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
What to read
One folder per host, named for the host and the UTC time, with each collection as CliXml, which keeps the objects' properties and types, and a hash of every file.
What it does not prove
That the collection is complete. Record what failed as well as what succeeded; a missing file is a gap, not a clean result.
Which other hosts carry the same file?
$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.Count
What to read
Each match, with the host it came from in PSComputerName. $using: passes your local value into the remote session.
What it does not prove
That a host is clean because it returned nothing. A host in $failed never answered; it is unknown, not clear.

Working with output 4

Investigation is mostly shaping results: picking columns, grouping, comparing with a baseline and saving in a form someone else can read.

How do I add a computed column?
Get-Process | Select-Object Name, Id, @{ n = "MB"; e = { [math]::Round($_.WorkingSet64 / 1MB, 1) } }, @{ n = "Started"; e = { $_.StartTime } }
What to read
A hashtable with n (name) and e (expression) adds a column computed for each object.
What it does not prove
Anything new: it only reshapes what the command returned.
How do I count by a field?
Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4625 } -MaxEvents 2000 | Group-Object { $_.Properties[19].Value } | Sort-Object Count -Descending | Select-Object Count, Name -First 10
What to read
Failed logons counted by source address (field 19 in 4625's data). Counting is how a spray stands out.
What it does not prove
Field positions differ between event IDs; the property function above is safer than an index.
What changed since the baseline?
$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
What to read
Services added (=>), removed (<=) or changed, against a snapshot saved earlier with Export-Clixml.
What it does not prove
Changes that were reverted before the second snapshot.
How do I save results for another tool?
$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.xml
What to read
CSV for spreadsheets and SIEM upload, JSON for scripts and other tools, CLIXML to reload the objects in PowerShell with their types.
What it does not prove
Nested properties in CSV, which flattens them to text; use JSON or CLIXML for those.

Contain 5

Stop an account or a host once the collections are saved. Each of these changes the evidence, so record when you ran it.

How do I disable a domain account?
Disable-ADAccount -Identity jdoe Get-ADUser jdoe -Properties Enabled, LockedOut | Select-Object Enabled, LockedOut
What to read
The account can no longer sign in once the change reaches the domain controller the attacker uses; check it on each site's controller if replication is slow.
What it does not prove
That the user is out. Sessions already signed in keep running; find them with klist sessions and the logon events, and end them on each host.
Is the host cut off from the network?
Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction Test-NetConnection -ComputerName ws-0142 -Port 445 # run from another host
What to read
Whether each firewall profile is on and blocks by default, then whether another host can still reach this one over SMB. TcpTestSucceeded False is the result you want.
What it does not prove
Full isolation. One port closed is one port; test the management and remote access ports you care about too.
How do I cut a host off but keep my own access?
New-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 True
What to read
Everything blocked except your responder host. Use it where Defender for Endpoint isolation is not available.
What it does not prove
That it holds. A local administrator can undo it; a domain policy refresh can too.
How do I disable a local account and a service?
Disable-LocalUser -Name "support" Stop-Service -Name "SuspectSvc" -Force Set-Service -Name "SuspectSvc" -StartupType Disabled Disable-ScheduledTask -TaskName "Updater" -TaskPath "\"
What to read
The account, the service and the task stop working without being deleted, so they stay as evidence.
What it does not prove
That nothing else restarts them. Look for a second persistence mechanism.
How do I quarantine a file without deleting it?
$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"
What to read
The file is moved out of its path and renamed so it cannot run by double-click, with its hash as the name.
What it does not prove
That it has not already run. Check process events for the hash.

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.

Where has the account signed in from?
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 } }
What to read
Recent sign-ins with address, application and result; ErrorCode 0 is a success. A successful sign-in from an address the user has never used, soon after failures, is the case to open.
What it does not prove
That the account was not used elsewhere. A stolen session token is used without a fresh sign-in, so look at the non-interactive sign-ins and the audit log too.
Which authentication methods are registered?
Connect-MgGraph -Scopes "UserAuthenticationMethod.Read.All" Get-MgUserAuthenticationMethod -UserId jdoe@contoso.com | Select-Object Id, @{ n = "Type"; e = { $_.AdditionalProperties["@odata.type"] } }
What to read
Every method on the account: password, authenticator app, phone, FIDO2 key. A method added during the incident lets the attacker pass MFA after a password reset.
What it does not prove
When a method was added. The Entra audit log records registrations with their time and the session that made them.
How do I end the account's cloud sessions?
Connect-MgGraph -Scopes "User.ReadWrite.All", "User.RevokeSessions.All" Update-MgUser -UserId jdoe@contoso.com -AccountEnabled:$false Revoke-MgUserSignInSession -UserId jdoe@contoso.com
What to read
The account is disabled, and its refresh tokens and browser session cookies are invalidated, so applications must send the user back to sign in.
What it does not prove
That access ends at once. Microsoft notes a delay of a few minutes, and an access token already issued is not a refresh token; remove any methods the attacker registered before re-enabling the account.
Which inbox rules and forwarding exist across all mailboxes?
Connect-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 }
What to read
Every rule that forwards, redirects, deletes or moves mail, tenant-wide.
What it does not prove
Mailbox-level forwarding, which is not a rule: check ForwardingSmtpAddress on Get-Mailbox as well.
Is mailbox auditing on?
Get-AdminAuditLogConfig | Select-Object UnifiedAuditLogIngestionEnabled Get-Mailbox -ResultSize Unlimited | Where-Object AuditEnabled -eq $false | Select-Object UserPrincipalName
What to read
Whether the unified audit log is ingesting, and any mailbox with auditing turned off.
What it does not prove
Which actions are audited per mailbox. AuditOwner, AuditDelegate and AuditAdmin on Get-Mailbox list them.
Which mail flow rules forward or redirect mail?
Get-TransportRule | Where-Object { $_.RedirectMessageTo -or $_.BlindCopyTo -or $_.AddToRecipients } | Select-Object Name, State, RedirectMessageTo, BlindCopyTo, AddToRecipients
What to read
Organization-wide rules that copy or redirect mail, which affect every mailbox at once.
What it does not prove
Who created a rule. The admin audit log records New-TransportRule.
What changed in the directory recently?
Connect-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 } }
What to read
Directory changes since a date: role assignments, consents, method registrations, app credentials.
What it does not prove
Anything older than the retention: 7 days on Entra ID Free, 30 on P1 and P2.
Which applications have credentials, and when do they expire?
Connect-MgGraph -Scopes "Application.Read.All" Get-MgApplication -All | ForEach-Object { $a = $_ $a.PasswordCredentials | Select-Object @{ n = "App"; e = { $a.DisplayName } }, DisplayName, StartDateTime, EndDateTime }
What to read
Every client secret on every app registration. A secret created during the incident is a backdoor.
What it does not prove
Secrets on service principals, which are separate: check Get-MgServicePrincipal as well.
Which delegated permission grants cover the whole tenant?
Connect-MgGraph -Scopes "Directory.Read.All" Get-MgOauth2PermissionGrant -All | Where-Object ConsentType -eq "AllPrincipals" | Select-Object ClientId, Scope
What to read
Grants consented for everyone. Look up each ClientId with Get-MgServicePrincipal.
What it does not prove
Application permissions (app roles), which are a different kind of grant.
Which users does Identity Protection rate as risky?
Connect-MgGraph -Scopes "IdentityRiskyUser.Read.All" Get-MgRiskyUser -Filter "riskLevel eq 'high'" | Select-Object UserPrincipalName, RiskLevel, RiskState, RiskLastUpdatedDateTime
What to read
Users currently at high risk.
What it does not prove
Why. The risk detections for each user hold the reasons.
Which Conditional Access policies are on, and which are report-only?
Connect-MgGraph -Scopes "Policy.Read.All" Get-MgIdentityConditionalAccessPolicy -All | Select-Object DisplayName, State, ModifiedDateTime
What to read
Each policy's state: enabled, disabled or enabledForReportingButNotEnforced. A policy changed during the incident is worth reading.
What it does not prove
Who changed it. The directory audit log records policy updates.

Quick lookup

QuestionReach 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.