Native Windows Forensic Commands for Incident Response
When KAPE cannot be deployed and EZ Tools are not installed, Windows still ships with what you need to preserve the volatile state.
Collection with PowerShell and cmd, grouped by the question each command answers: the system profile, processes with command lines, parents and owners, loaded modules and drivers, sessions and accounts, network connections, shares and pivots, persistence, Defender, event logs, files and user activity; then exporting the logs and hives for full-tool analysis, collecting across many hosts, and containing. Every command checked against its Microsoft reference page.
You are on a call with a worried sysadmin. A server is behaving strangely and they think it is compromised. You need the volatile state, running processes, network connections and who is logged on, before anyone reboots it. There is no KAPE on the host and no EZ Tools. There is a command prompt and PowerShell. This page is what you tell them to run.
A dedicated tool beats a native command at its own job: KAPE copies files the operating system has locked, and EZ Tools parse binary artifacts into timelines. But a tool has to reach the host, and that can be blocked: application control refuses unknown binaries, removable media is disabled, change control will not allow new software on a production server today, and in an insider case a visible tool warns the subject. Built-in, signed Windows binaries are far more likely to be allowed than anything you copy across, and they need no transfer.
The commands below are grouped by the question they answer, collect to files so the output can be preserved and hashed, and run in both Windows PowerShell 5.1 and PowerShell 7. Every cmdlet and parameter on the page is checked against its Microsoft reference page, and every native command's switches against its windows-commands page. For the PowerShell an analyst runs while investigating, rather than collecting, see the PowerShell for Security Analysts cheatsheet.
Before you collect: record what you did
Every command you run changes the host a little and is itself recorded. Collect in order of volatility (processes and connections first, then sessions and persistence, then logs and files), write everything to one evidence folder, and keep a transcript so the report can say exactly what was run and when. Run elevated: the Security log, other users' process owners and the WMI subscription namespace need it.
# One evidence folder per host, and a transcript of the session
$ev = "C:\IR\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HHmm)"
New-Item -ItemType Directory -Path $ev -Force | Out-Null
Start-Transcript -Path "$ev\transcript.txt"
System profile: what is this host, and what is its clock?
Record the host's identity, build and clock before anything else. Every timestamp you collect is set against them, and the build decides which artifacts and logs exist at all. This takes seconds and changes nothing.
# Name, domain, OS build, install date and last boot
Get-CimInstance Win32_ComputerSystem | Select-Object Name, Domain, Model |
Export-Csv "$ev\computer.csv" -NoTypeInformation
Get-CimInstance Win32_OperatingSystem |
Select-Object Caption, Version, BuildNumber, InstallDate, LastBootUpTime |
Export-Csv "$ev\os.csv" -NoTypeInformation
# The zone the host keeps local time in, and the true time now in UTC
Get-TimeZone | Select-Object Id, BaseUtcOffset, SupportsDaylightSavingTime
(Get-Date).ToUniversalTime().ToString('o') | Out-File "$ev\clock_utc.txt"
# Installed updates, oldest first
Get-HotFix | Sort-Object InstalledOn |
Select-Object HotFixID, Description, InstalledOn, InstalledBy |
Export-Csv "$ev\hotfixes.csv" -NoTypeInformation
Reading it: a LastBootUpTime inside the incident window means memory from before it is gone, and Run keys and services set to start at boot have already fired. A build of 22000 or higher is Windows 11 even where the caption still says Windows 10. Compare the host's clock with your own: a skew of minutes moves every local event against your other sources. Get-HotFix lists Windows updates only, with a date and no time.
Processes: what is running and who started it?
Process state is the most volatile evidence on the host, so it comes first. The inventory below records each process's command line, path, parent and owner. It reads the process table once and looks parents up from that copy, so a parent that has exited shows as missing rather than being matched to a later process.
# Process inventory: command line, path, parent and owner
$all = Get-CimInstance Win32_Process
$byPid = @{}
foreach ($p in $all) { $byPid[$p.ProcessId] = $p }
$all | ForEach-Object {
$o = Invoke-CimMethod -InputObject $_ -MethodName GetOwner
$parent = $byPid[$_.ParentProcessId]
[PSCustomObject]@{
PID = $_.ProcessId
Name = $_.Name
PPID = $_.ParentProcessId
ParentName = if ($parent) { $parent.Name } else { 'not running' }
CommandLine = $_.CommandLine
Path = $_.ExecutablePath
Owner = if ($o.User) { "$($o.Domain)\$($o.User)" } else { '' }
Created = $_.CreationDate
SessionId = $_.SessionId
}
} | Export-Csv "$ev\processes.csv" -NoTypeInformation
What to look for:
Parent and child pairs that do not belong together. services.exe starts svchost.exe, explorer.exe starts what the user opens, and a shell starts what was typed into it. outlook.exe or winword.exe starting powershell.exe is how a phishing attachment runs (T1566.001); wmiprvse.exe starting a shell is WMI remote execution (T1047); rundll32.exe with an unusual parent or no command line is a common staging step (T1218.011).
System names in the wrong folder. svchost.exe belongs in C:\Windows\System32\. One running from C:\Users\Public\ or C:\ProgramData\ is a payload named after a system process (T1036.005).
Encoded or hidden PowerShell. -enc or -EncodedCommand, -w hidden and -nop on a powershell.exe command line, or a long Base64 string, are rare in administration and common in attacks (T1027.010).
For a binary that looks wrong, record its hash and signature before anyone deletes it:
# Hash and signature of a suspect binary
$f = 'C:\ProgramData\Microsoft\Crypto\svchost.exe'
Get-FileHash -Path $f -Algorithm SHA256
Get-AuthenticodeSignature -FilePath $f |
Select-Object Status, StatusMessage, SignerCertificate
Finding: The process inventory shows svchost.exe (PID 7284) running from C:\ProgramData\Microsoft\Crypto\svchost.exe with parent wmiprvse.exe (PID 3012). The genuine svchost.exe lives in C:\Windows\System32\, and the file is unsigned. The path, the missing signature and the WMI parent indicate a masquerading payload started by WMI remote execution.
Does not prove
What the payload does, when it first arrived, or which host or account sent the WMI command.
Next step
Hash and preserve the binary. Check PID 7284 in the connections output. Look for the originating logon (4624 type 3) around the process creation time.
Modules, drivers and pipes: what is loaded in memory?
A process can be clean on disk and still load a malicious DLL, and a kernel driver runs below every tool on this page. These lists are short, change at runtime, and are gone at reboot.
# DLLs loaded by a suspect process
Get-Process -Id 7284 -Module -EA 0 | Select-Object ModuleName, FileName |
Export-Csv "$ev\modules_7284.csv" -NoTypeInformation
# Kernel drivers and the file each loads from
Get-CimInstance Win32_SystemDriver |
Select-Object Name, State, StartMode, PathName |
Export-Csv "$ev\drivers.csv" -NoTypeInformation
# Named pipes open now
Get-ChildItem \\.\pipe\ | Select-Object Name |
Export-Csv "$ev\pipes.csv" -NoTypeInformation
What to look for: modules loaded from user-writable folders, or with a system DLL's name from the wrong folder (side-loading, T1574.001); drivers whose path is outside System32\drivers or that no vendor on the host would install; pipe names that are random, or that follow the defaults of a known command-and-control framework. Get-Process -Module needs an elevated prompt and matching bitness to read another process's modules. Anything injected without a backing file does not appear here at all: that needs a memory image (see the memory forensics reference).
Sessions: who is on this host right now?
Interactive and Remote Desktop sessions come from query user (quser), and inbound file-share sessions from Get-SmbSession. An administrator logged on from a workstation they do not use, or an SMB session from a host that never talks to this server, is a lead to follow into the logon events.
# Interactive and RDP sessions, then inbound SMB sessions
quser | Out-File "$ev\sessions_quser.txt"
Get-SmbSession -ErrorAction SilentlyContinue |
Select-Object ClientComputerName, ClientUserName, NumOpens |
Export-Csv "$ev\smb_sessions.csv" -NoTypeInformation
quser reports nothing for network logons such as SMB or WinRM, and an attacker who has already logged off leaves no session at all. The logon events below cover both.
Accounts: who can log on here, with what rights?
Start with the account you are collecting as, then the local accounts and the groups that give remote or administrative access, then the profiles, which show every account that has logged on interactively at some point.
# The collecting account: groups and privileges
whoami /all > "$ev\whoami.txt"
# Local accounts, then members of the groups that grant access
Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, SID |
Export-Csv "$ev\local_users.csv" -NoTypeInformation
foreach ($g in 'Administrators', 'Remote Desktop Users',
'Remote Management Users') {
Get-LocalGroupMember -Group $g -EA 0 |
Select-Object @{N='Group';E={$g}}, Name, ObjectClass,
PrincipalSource |
Export-Csv "$ev\group_members.csv" -NoTypeInformation -Append
}
# Profiles: every account that has logged on interactively
Get-CimInstance Win32_UserProfile |
Select-Object LocalPath, SID, LastUseTime, Loaded, Special |
Export-Csv "$ev\profiles.csv" -NoTypeInformation
What to look for: a local account created or re-enabled recently, a PasswordLastSet inside the window on an account nobody uses, domain accounts or groups added to the local Administrators or Remote Desktop Users group, and a profile for a service or domain admin account on a workstation. A profile is created at an account's first interactive logon, so a new one is a dated first logon. In cmd, net user lists the local accounts.
Network: who is this host talking to?
# TCP connections and listeners, mapped to the owning process
Get-NetTCPConnection -State Established, Listen |
Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort,
State, OwningProcess,
@{N='Process';E={(Get-Process -Id $_.OwningProcess -EA 0).Path}} |
Export-Csv "$ev\tcp.csv" -NoTypeInformation
# UDP endpoints (listeners such as a rogue DNS or tunnel)
Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess |
Export-Csv "$ev\udp.csv" -NoTypeInformation
# DNS cache: names resolved recently, kept until their time to live runs out
Get-DnsClientCache |
Select-Object Entry, Name, Type, Status, TimeToLive, Data |
Export-Csv "$ev\dns_cache.csv" -NoTypeInformation
# Neighbor (ARP) table: local hosts this one has exchanged traffic with
Get-NetNeighbor | Where-Object State -ne 'Unreachable' |
Select-Object IPAddress, LinkLayerAddress, State, InterfaceAlias |
Export-Csv "$ev\neighbors.csv" -NoTypeInformation
Reading it: take every established connection to an outside address, find its process by PID in the process inventory, and ask whether that program should talk to the internet at all. A browser should; svchost.exe from ProgramData should not. The DNS cache names the remote address: a name resolving to it says whether the connection went to a known service or to a host registered last week. Type in the DNS cache is the record type number (1 is A, 5 is CNAME, 28 is AAAA).
The firewall shows whether someone opened a door. Check that each profile is on, and list the inbound allow rules so a new one stands out:
# Firewall profiles, then enabled inbound allow rules
Get-NetFirewallProfile |
Select-Object Name, Enabled, DefaultInboundAction, LogFileName
Get-NetFirewallRule -Enabled True -Direction Inbound -Action Allow |
Select-Object DisplayName, Profile, Group |
Export-Csv "$ev\fw_inbound_allow.csv" -NoTypeInformation
Finding: PID 7284 (svchost.exe from C:\ProgramData\) holds an established TCP connection to 203.0.113.47:443. The DNS cache holds cdn-update.example resolving to 203.0.113.47, a name the organization does not own and that imitates an update service.
Does not prove
What data has crossed the connection, how long it has been open, or whether other hosts talk to the same address.
Next step
Block 203.0.113.47 and the name at the perimeter, isolate the host, and search for the same address and name across the fleet in your EDR or proxy logs.
Shares, mapped drives and pivots
File shares are how data leaves and how attackers move. Collect what this host offers, what it has open, what it has mapped elsewhere, and the routing and forwarding settings an attacker can change to relay traffic through it.
# Shares this host offers, and files open on them now
Get-SmbShare | Select-Object Name, Path, Description, CurrentUsers |
Export-Csv "$ev\smb_shares.csv" -NoTypeInformation
Get-SmbOpenFile | Select-Object ClientComputerName, ClientUserName, Path |
Export-Csv "$ev\smb_openfiles.csv" -NoTypeInformation
# Drives mapped from this session to other hosts
Get-SmbMapping | Select-Object LocalPath, RemotePath, Status |
Export-Csv "$ev\smb_mappings.csv" -NoTypeInformation
# Routes, then the hosts file
Get-NetRoute | Select-Object DestinationPrefix, NextHop, InterfaceAlias,
RouteMetric | Export-Csv "$ev\routes.csv" -NoTypeInformation
Get-Content "$env:SystemRoot\System32\drivers\etc\hosts" |
Out-File "$ev\hosts.txt"
# Port forwarding rules and the system proxy
netsh interface portproxy show all > "$ev\portproxy.txt"
netsh winhttp show proxy > "$ev\winhttp_proxy.txt"
What to look for: a share pointing at a whole drive or a staging folder that is not a business share; open files on a share by an account or client that should not be there; a portproxy rule forwarding a local port to an internal host (T1090.001), which survives a reboot and turns this host into a relay; a WinHTTP proxy no one configured; and a hosts entry pinning a name. Get-SmbMapping shows the mappings of the session it runs in, not every user's: other users' mapped drives are in their NTUSER.DAT hives.
Persistence: what survives a reboot?
# Scheduled tasks with their actions and last run
Get-ScheduledTask | Where-Object State -ne 'Disabled' | ForEach-Object {
$i = Get-ScheduledTaskInfo -InputObject $_ -EA 0
[PSCustomObject]@{
Task = $_.TaskPath + $_.TaskName
Actions = ($_.Actions | ForEach-Object {
"$($_.Execute) $($_.Arguments)" }) -join '; '
RunAs = $_.Principal.UserId
LastRun = $i.LastRunTime
}
} | Export-Csv "$ev\tasks.csv" -NoTypeInformation
# Services and the binary each runs
Get-CimInstance Win32_Service |
Select-Object Name, DisplayName, State, StartMode, PathName, StartName |
Export-Csv "$ev\services.csv" -NoTypeInformation
# Run and RunOnce keys, machine and current user
$keys = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'
foreach ($k in $keys) {
if (Test-Path $k) {
Get-ItemProperty $k | Out-File "$ev\run_keys.txt" -Append
}
}
# Startup folders, all users and the current user
$sm = 'Microsoft\Windows\Start Menu\Programs\Startup'
Get-ChildItem "$env:ProgramData\$sm", "$env:APPDATA\$sm" -EA 0 |
Select-Object FullName, CreationTime, LastWriteTime
HKCU and the current user's Startup folder are the account running the collection. For other users, the per-user Run keys are in their NTUSER.DAT hives, which the registry export at the end preserves for offline parsing.
# WMI event subscriptions: filter, consumer and the binding between them
foreach ($c in '__EventFilter', 'CommandLineEventConsumer',
'ActiveScriptEventConsumer', '__FilterToConsumerBinding') {
Get-CimInstance -Namespace root\subscription -ClassName $c -EA 0 |
Export-Clixml "$ev\wmi_$c.xml"
}
What makes an entry suspicious: a binary in AppData, Temp, ProgramData, Public or a user profile; a name one character off a real Windows task or service; a service or task whose command is powershell, cmd, mshta, wscript, cscript or rundll32 with arguments; an account created recently or added to Administrators outside a change. Scheduled tasks (T1053.005), services (T1543.003), Run keys and Startup folders (T1547.001) and local accounts (T1136.001, collected under Accounts above) are the common mechanisms. A WMI event subscription (T1546.003) is rare in legitimate software, so any consumer bound to a filter deserves a close read.
# Logon hooks: Winlogon, IFEO debuggers and LSA packages
$nt = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Get-ItemProperty "$nt\Winlogon" | Select-Object Userinit, Shell
Get-ChildItem "$nt\Image File Execution Options" | ForEach-Object {
$d = (Get-ItemProperty $_.PSPath).Debugger
if ($d) { [PSCustomObject]@{ Program = $_.PSChildName; Debugger = $d } }
}
Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' |
Select-Object 'Security Packages', 'Authentication Packages',
'Notification Packages'
# BITS jobs for every user (Windows PowerShell, elevated)
Get-BitsTransfer -AllUsers -EA 0 |
Select-Object DisplayName, JobState, OwnerAccount, FileList
Userinit should be userinit.exe followed by a comma and nothing else, and Shell should be explorer.exe (T1547.004). Any Debugger value outside a developer's machine is an IFEO redirect (T1546.012). The LSA values hold Microsoft package names; anything else loads into lsass.exe at boot, and a notification package receives every new password in plain text. A BITS job fetching from or sending to an unfamiliar host is a download or exfiltration channel that survives reboots (T1197).
Defender: what has it seen, and was it told to look away?
# Protection state
Get-MpComputerStatus |
Select-Object AMRunningMode, RealTimeProtectionEnabled,
IsTamperProtected, AntivirusSignatureLastUpdated |
Export-Csv "$ev\defender_status.csv" -NoTypeInformation
# Every detection Defender still holds, with what it did about it
Get-MpThreatDetection |
Select-Object InitialDetectionTime, ThreatID, ProcessName, DomainUser,
Resources, ActionSuccess |
Export-Csv "$ev\defender_detections.csv" -NoTypeInformation
# Exclusions: paths, extensions and processes it skips
Get-MpPreference |
Select-Object ExclusionPath, ExclusionExtension, ExclusionProcess,
DisableRealtimeMonitoring | Format-List
What to look for: real-time protection off or the engine in passive mode on a host with no other antivirus, a detection whose ActionSuccess is False, and an exclusion for a user-writable folder, a script extension or a tool's process name (T1685). Run these elevated: current Defender versions hide the exclusion lists from non-administrators. The Defender operational log (5001, 5007) records when each setting changed.
Event logs: what happened, and when?
The queries below pull the events that answer the first questions of an incident. Each reads named fields by position, in the order the event's schema defines them. The Event ID reference lists what each ID means and where it is logged.
# 4624 successful logons in the last 7 days: account, type, source
Get-WinEvent -FilterHashtable @{LogName='Security';Id=4624
StartTime=(Get-Date).AddDays(-7)} -MaxEvents 5000 -EA 0 |
Select-Object TimeCreated,
@{N='Account';E={$_.Properties[5].Value}},
@{N='LogonType';E={$_.Properties[8].Value}},
@{N='Workstation';E={$_.Properties[11].Value}},
@{N='SourceIP';E={$_.Properties[18].Value}} |
Export-Csv "$ev\logons_4624.csv" -NoTypeInformation
# 4688 process creation (needs process creation auditing)
Get-WinEvent -FilterHashtable @{LogName='Security';Id=4688
StartTime=(Get-Date).AddDays(-1)} -MaxEvents 5000 -EA 0 |
Select-Object TimeCreated,
@{N='Process';E={$_.Properties[5].Value}},
@{N='CommandLine';E={$_.Properties[8].Value}},
@{N='Parent';E={$_.Properties[13].Value}} |
Export-Csv "$ev\proc_4688.csv" -NoTypeInformation
4688 is logged only when process creation auditing is on, and its CommandLine field is empty unless the policy "Include command line in process creation events" is also enabled. An empty column means the policy was off, not that the processes had no arguments.
| Logon type | Meaning |
|---|---|
| 2 | Interactive, at the console |
| 3 | Network: file shares, WinRM, most remote tools |
| 4 | Batch, such as a scheduled task |
| 5 | Service start |
| 7 | Unlock |
| 9 | NewCredentials (runas /netonly) |
| 10 | RemoteInteractive, Remote Desktop |
| 11 | Cached credentials, no domain controller reached |
# 7045 service installed
Get-WinEvent -FilterHashtable @{LogName='System';Id=7045} `
-MaxEvents 200 -EA 0 |
Select-Object TimeCreated,
@{N='Service';E={$_.Properties[0].Value}},
@{N='ImagePath';E={$_.Properties[1].Value}} |
Export-Csv "$ev\svc_7045.csv" -NoTypeInformation
# 4104 script blocks: Windows PowerShell 5.1 and PowerShell 7 log apart
foreach ($l in 'Microsoft-Windows-PowerShell/Operational',
'PowerShellCore/Operational') {
Get-WinEvent -FilterHashtable @{LogName=$l;Id=4104} `
-MaxEvents 1000 -EA 0 |
Select-Object TimeCreated,
@{N='ScriptBlock';E={$_.Properties[2].Value}} |
Export-Csv "$ev\ps_4104_$($l.Split('/')[0]).csv" `
-NoTypeInformation
}
# 1102 Security log cleared; System 104 records other logs cleared
Get-WinEvent -FilterHashtable @{LogName='Security';Id=1102} `
-MaxEvents 50 -EA 0 | Select-Object TimeCreated, Message
Get-WinEvent -FilterHashtable @{LogName='System';Id=104} `
-MaxEvents 50 -EA 0 | Select-Object TimeCreated, Message
A cleared log (T1685.005) is evidence in itself: note the time and the account in the message, and treat everything before it as missing rather than absent. PowerShell 7 writes its script blocks to its own PowerShellCore/Operational log, so a host with both versions needs both reads.
# Account, group, task, service and audit changes in one pass
$ids = 4720, 4728, 4732, 4756, 4697, 4698, 4719, 4648
Get-WinEvent -FilterHashtable @{LogName='Security';Id=$ids
StartTime=(Get-Date).AddDays(-7)} -EA 0 |
Select-Object TimeCreated, Id,
@{N='Summary';E={($_.Message -split "`n")[0]}} |
Export-Csv "$ev\security_changes.csv" -NoTypeInformation
# How much history each log can hold, and the audit policy in force
Get-WinEvent -ListLog Security, System, Application,
'Microsoft-Windows-PowerShell/Operational' -EA 0 |
Select-Object LogName, MaximumSizeInBytes, RecordCount, IsEnabled
auditpol /get /category:* > "$ev\auditpol.txt"
The first query reads the first line of each event's message, which names the change; the full message, with the subject and target accounts, is in the exported .evtx. The second shows how far back each log can reach: a Security log capped at its default size may hold only days on a busy server, which is why the export below matters. auditpol shows which subcategories are on now, and so which of the events above could exist at all.
Files: what arrived recently?
Native commands cannot parse Prefetch or Amcache, but they can list what is there and show where new executables landed. The file times below are the file system's own and can be changed by an attacker; treat them as leads to confirm in the $MFT and Prefetch once a full tool can parse them.
# Prefetch files by last write (where Prefetch is enabled)
Get-ChildItem C:\Windows\Prefetch -Filter *.pf -EA 0 |
Sort-Object LastWriteTime -Descending |
Select-Object Name, CreationTime, LastWriteTime |
Export-Csv "$ev\prefetch_list.csv" -NoTypeInformation
# Executables and scripts written in the last 7 days to user-writable paths
$since = (Get-Date).AddDays(-7)
Get-ChildItem C:\Users, C:\ProgramData, C:\Windows\Temp -Recurse -File `
-Include *.exe, *.dll, *.ps1, *.bat, *.vbs, *.hta -Force -EA 0 |
Where-Object LastWriteTime -gt $since |
Select-Object FullName, Length, CreationTime, LastWriteTime |
Export-Csv "$ev\recent_executables.csv" -NoTypeInformation
Shadow copies hold earlier versions of the volume, and deleting them is a ransomware step (T1490). List what exists; on a server that keeps them, an empty list is itself a finding.
vssadmin list shadows
More file questions, with the cmdlets that answer them, are in the PowerShell for Security Analysts cheatsheet.
# Alternate data streams other than the normal mark of the web
Get-ChildItem C:\Users, C:\ProgramData -Recurse -File -Force -EA 0 |
Get-Item -Stream * -EA 0 |
Where-Object Stream -notin ':$DATA', 'Zone.Identifier' |
Select-Object FileName, Stream, Length |
Export-Csv "$ev\ads.csv" -NoTypeInformation
# Hash and signature of every file in a suspect folder
Get-ChildItem C:\ProgramData\Microsoft\Crypto -File -Force -EA 0 |
ForEach-Object {
$s = Get-AuthenticodeSignature -FilePath $_.FullName
[PSCustomObject]@{
Path = $_.FullName
SHA256 = (Get-FileHash -Path $_.FullName).Hash
Signature = $s.Status
Signer = $s.SignerCertificate.Subject
}
} | Export-Csv "$ev\folder_hashes.csv" -NoTypeInformation
A stream other than the main data and Zone.Identifier can hide a payload or a script (T1564.004). A file whose CreationTime is later than its LastWriteTime was usually copied or extracted here, keeping an older modified time from its source, which is normal for installers and also how a planted tool can look old.
User activity: what did the people on this host do?
Several user artifacts are plain files that native commands can copy or read: PowerShell console history, recent-item shortcuts, the mark of the web on downloads, and the Recycle Bin. The binary ones (ShellBags, jump lists, UserAssist) wait for the full tools; the Windows forensic artifacts reference lists them all.
# PowerShell console history for every profile
$ps = 'AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine'
Get-ChildItem "C:\Users\*\$ps\*_history.txt" -Force -EA 0 |
ForEach-Object {
$u = $_.FullName.Split('\')[2]
Copy-Item -Path $_.FullName -Destination "$ev\$u-$($_.Name)"
}
# Downloads, with where each came from (Zone.Identifier)
Get-ChildItem C:\Users\*\Downloads -File -Force -EA 0 | ForEach-Object {
$z = Get-Content -Path $_.FullName -Stream Zone.Identifier -EA 0
[PSCustomObject]@{
File = $_.FullName
Created = $_.CreationTime
Source = ($z -join ' ')
}
} | Export-Csv "$ev\downloads.csv" -NoTypeInformation
# Recent-item shortcuts and the Recycle Bin
$rec = 'AppData\Roaming\Microsoft\Windows\Recent'
Get-ChildItem "C:\Users\*\$rec\*.lnk" -Force -EA 0 |
Select-Object FullName, CreationTime, LastWriteTime |
Export-Csv "$ev\recent_lnk.csv" -NoTypeInformation
Get-ChildItem 'C:\$Recycle.Bin' -Recurse -Force -EA 0 |
Select-Object FullName, Length, LastWriteTime |
Export-Csv "$ev\recycle_bin.csv" -NoTypeInformation
Reading it: the history files are what someone typed at a PowerShell prompt, in order, and they often hold the attacker's discovery and download commands. PSReadLine leaves out lines containing words such as password and token, and records nothing from scripts or remote shells. The Source column holds the URL a file was downloaded from, where the browser wrote one. In the Recycle Bin, each $I file is the record of a deletion (original path and time) and its $R twin is the content; RBCmd parses the $I files later.
Preserve for the full tools
This is the step that turns a native collection into a full investigation. wevtutil epl exports the event logs as .evtx files, and reg save writes copies of the loaded registry hives. Both run on the host with nothing installed; the parsing happens later, on your workstation.
# Export the event logs as .evtx
$logs = 'Security', 'System', 'Application',
'Microsoft-Windows-PowerShell/Operational', 'PowerShellCore/Operational',
'Microsoft-Windows-Sysmon/Operational',
'Microsoft-Windows-TaskScheduler/Operational',
'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
foreach ($l in $logs) {
$out = "$ev\" + ($l -replace '[/\\ ]', '_') + '.evtx'
wevtutil epl $l $out /ow:true 2>$null
if ($LASTEXITCODE -eq 0) { Write-Host "Exported $l" }
}
# Copies of the loaded machine hives (SAM and SECURITY hold secrets)
foreach ($h in 'SYSTEM', 'SOFTWARE', 'SAM', 'SECURITY') {
reg save "HKLM\$h" "$ev\$h.hiv" /y
}
A log the host does not have (Sysmon, PowerShell 7) fails quietly and is skipped. reg save copies hives the registry has loaded; it cannot reach files the system holds locked outside the registry, such as $MFT, the USN journal or Amcache.hve. Those need a raw-disk collector such as KAPE.
On the workstation, EvtxECmd parses the exported logs into one CSV with its event maps applied:
EvtxECmd.exe -d "E:\Evidence\HOST01" --csv "E:\Parsed\HOST01"
The KAPE and EZ Tools cheatsheet covers EvtxECmd, RECmd for the saved hives, and the collection targets for everything native commands cannot copy.
# Close the collection: stop the transcript, then hash every file
Stop-Transcript
$h = Get-ChildItem $ev -File | Get-FileHash -Algorithm SHA256
$h | Export-Csv "$ev\hashes.csv" -NoTypeInformation
Collecting from many hosts
When the question is which other hosts show the same thing, PowerShell remoting runs one collection across a list of hosts and labels each row with the host it came from. Use it from an administration host, with Kerberos, rather than logging on to each machine interactively.
# The same question on many hosts, one CSV with a PSComputerName column
$targets = Get-Content C:\IR\hosts.txt
Invoke-Command -ComputerName $targets -ThrottleLimit 16 -ScriptBlock {
Get-NetTCPConnection -State Established |
Where-Object RemoteAddress -eq '203.0.113.47' |
Select-Object LocalPort, RemoteAddress, RemotePort, OwningProcess
} | Export-Csv C:\IR\fleet_203.0.113.47.csv -NoTypeInformation
What it leaves on each target: a network logon (4624, type 3) for the collecting account, the commands running under wsmprovhost.exe, a WinRM operational event (91 on the target, 6 on the host you ran it from), and the script block in 4104 where logging is on. Write that down, so your own collection is not later read as the attacker's lateral movement. Microsoft's logon-type reference lists a successful Remote Desktop logon as leaving reusable credentials on the destination and PowerShell WinRM as not doing so, unless CredSSP is used, which does.
Contain after you collect
Containment destroys evidence: stopping a process loses its memory, and blocking its connection ends the traffic you might have captured. Do it after collection, in this order, and record each step in the transcript.
# 1. Preserve the process first: its hash and a copy of its binary
$p = Get-Process -Id 7284
Get-FileHash -Path $p.Path -Algorithm SHA256 |
Export-Csv "$ev\pid7284_hash.csv" -NoTypeInformation
Copy-Item -Path $p.Path -Destination "$ev\pid7284.bin"
# 2. Then stop it
Stop-Process -Id 7284 -Force
# 3. Block the address it talked to, both directions
New-NetFirewallRule -DisplayName 'IR block 203.0.113.47 out' `
-Direction Outbound -RemoteAddress 203.0.113.47 -Action Block
New-NetFirewallRule -DisplayName 'IR block 203.0.113.47 in' `
-Direction Inbound -RemoteAddress 203.0.113.47 -Action Block
# 4. Disable a local account the attacker created
Disable-LocalUser -Name 'svc_backup'
Take a memory image before step 2 if you can (see the memory forensics reference): once the process stops, its decrypted configuration and injected code are gone. A firewall rule does not cut a connection that is tunneled through an allowed proxy, and it can be removed by anyone with administrator rights on the host, so network-level isolation (EDR containment or the switch port) is the stronger control. For a domain account, disable it in Active Directory: Disable-LocalUser acts on local accounts only.
When PowerShell is not available
Where PowerShell is blocked or constrained, cmd still covers the core of the collection. WMIC is no longer an option on current Windows: Microsoft has removed it from Windows 11, version 24H2 and later, so use these instead.
REM Processes, owners, services
tasklist /v /fo csv > C:\IR\tasklist.csv
tasklist /svc > C:\IR\tasklist_svc.txt
REM Connections with PIDs
netstat -ano > C:\IR\netstat.txt
REM DNS cache, sessions, tasks
ipconfig /displaydns > C:\IR\dns_cache.txt
quser > C:\IR\sessions.txt
schtasks /query /fo csv /v > C:\IR\tasks.csv
REM Run keys
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /s
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /s
REM Export a log
wevtutil epl Security C:\IR\Security.evtx /ow:true
REM System, accounts, modules and drivers
systeminfo > C:\IR\systeminfo.txt
whoami /all > C:\IR\whoami.txt
net user > C:\IR\net_user.txt
tasklist /m > C:\IR\tasklist_modules.txt
driverquery /v /fo csv > C:\IR\drivers.csv
REM Audit policy, proxy and port forwarding
auditpol /get /category:* > C:\IR\auditpol.txt
netsh winhttp show proxy > C:\IR\proxy.txt
netsh interface portproxy show all > C:\IR\portproxy.txt
netstat -ano gives the PID but not the program; match it to tasklist's PID column. tasklist /v shows the owner but not the command line, which cmd cannot read without WMIC; the 4688 events are the fallback where command-line auditing is on.
Native commands or dedicated tools?
What native commands give you: they are already on the host, need no approval or transfer, and are the least likely thing on the box to be blocked. They are the fastest route from an alert to preserved volatile state.
What they cannot do: read files the system holds locked outside the registry ($MFT, the USN journal, Amcache.hve), parse binary artifacts such as Prefetch, Amcache and ShimCache into readable records, build a timeline, or collect across a fleet.
The workflow when a tool cannot reach the host: collect natively on the host, preserve the logs and hives as above, move the evidence folder to your workstation, and parse it there with EvtxECmd and RECmd. Analyze the native CSVs alongside the parsed output. Follow with a raw-disk collection when the tool can be deployed.
The reasonable mistake
"Native commands are not forensically useful; wait for the proper tools." They cannot reach locked files or parse binary artifacts. But they do capture processes with command lines and parents, connections with their process, sessions, scheduled tasks, services, Run keys, local accounts, WMI subscriptions, the DNS cache, firewall state, the event logs and the registry hives, and that is enough to decide whether to contain. The volatile part is gone once the host reboots, and a tool approved two hours later cannot get it back. Collect natively now and follow with the full collection.
From collecting evidence to proving what happened
These commands collect the state of a host. Windows Endpoint Investigation teaches the method that follows: correlating execution, file system, registry and event log artifacts into a timeline of the intrusion you can defend.
Explore the courseWeekly security engineering insights
Detection techniques, architecture patterns, and operational judgment, every Tuesday.
No spam. Unsubscribe anytime.