Practice library / Windows, Active Directory and macOS
Workbook · Easy · 3 hours
Windows Command Line & PowerShell
CMD and PowerShell commands, scripts, and automation for enterprise environments.
On this page 4 sections
The Windows command line is a fast way to operate a Windows host, and it is also how many intruders work once a shell is open. The workbook covers CMD for day-to-day navigation and file work, then PowerShell for scripting, enumeration and automation. PowerShell is a full language on top of .NET, so it reads the registry, the event log, services, processes and Active Directory objects without any extra tool. The commands fit together because each one feeds the next: Get-Process pipes to Where-Object, output goes to CSV, and a script loops over hosts. The workbook also explains what each command leaves behind in the event log, so defenders can see the same work.
What You'll Learn
- Navigate and manage Windows from the console
- Use core CMD commands
- Write basic PowerShell
- Enumerate systems from the command line
- Know what your commands leave behind in the event log
About This Workbook
On Windows engagements you often have only a console. Sometimes that is a deliberate choice — a jump box, a Server Core install, a session over WinRM. Sometimes it is what you were handed. Either way, the skill you need is the same: describe a machine, change it, and prove what you did, without a mouse.
This workbook builds that fluency in the two shells that sit side by side on every modern Windows box. cmd.exe moves text, has been stable for decades, and is present when nothing else is. PowerShell moves objects, which changes how you think about every pipeline you write. You need both: CMD because scripts, scheduled tasks and service definitions are still full of it, PowerShell because anything beyond a one-liner is impractical in CMD.
Authorisation. The enumeration in Chapter 3 is read-only reconnaissance, but it is still activity on someone else's computer. Run it only against systems you own or have written permission to test, and only within the scope you were given. "I was only looking" is not a defence anywhere it matters.
Open a console now and follow along. Reading shell commands without running them is how people end up able to recognise a flag but not produce it.
Chapter 1 — The Command Prompt
Getting things done with classic CMD.
cmd.exe has two kinds of command. Internal commands — dir, cd, copy, set, echo, type, del — are code inside cmd.exe itself. There is no dir.exe on disk. External commands are real executables, almost all of them in C:\Windows\System32: ping.exe, findstr.exe, tasklist.exe, sc.exe, reg.exe. The distinction matters the moment you try to call dir from something that is not a shell, or wonder why where dir finds nothing.
Two commands answer most "how does this work" questions without leaving the console:
help
help dir
dir /?
where findstrhelp with no argument lists the internal commands. dir /? — the /? switch — is the universal help convention for external commands too. where tells you which file on %PATH% would actually run.
Navigation
cd C:\Users\Public
cd ..
cd /d D:\Tools
pushd \\fileserver\share\logs
popdcd .. goes up one level. The one that catches people out is cd D:\Tools from a C: prompt: it changes the current directory of the D: drive and leaves you exactly where you were. cd /d changes drive and directory together, which is almost always what you meant.
pushd and popd are a stack of directories. Given a UNC path, pushd maps the share to a free drive letter and moves you there; popd unmaps it again. That is the cleanest way to work on a remote share from a shell.
Listing is dir, and its switches earn their keep:
dir
dir /a
dir /a:h
dir /s /b C:\inetpub\*.config
dir /o:-d/a shows all entries including hidden and system files — files a plain dir silently omits. /a:h shows only the hidden ones. /s recurses; /b strips the headers and summary and prints bare paths, which is what you want when the output is going into another command. /o:-d sorts by date, newest first, which is how you find what changed.
File and system commands
Reading and searching files:
type C:\Windows\System32\drivers\etc\hosts
type biglog.txt | more
findstr /s /i /m /c:"password" *.config *.xml *.ini
findstr /n /i "failed" C:\Logs\app.logfindstr is the CMD equivalent of grep and it is worth learning properly. /s recurses from the current directory, /i is case-insensitive, /m prints only the names of matching files (not the matching lines), /n prefixes line numbers, and /c:"..." treats the argument as one literal string rather than a list of search terms. Without /c:, findstr "web config" searches for web or config, which is a common and quiet source of wrong answers.
Processes and services:
tasklist
tasklist /svc
tasklist /v /fi "USERNAME ne NT AUTHORITY\SYSTEM"
taskkill /PID 4312 /F
sc query state= all
sc qc Spoolertasklist /svc maps each process to the services hosted inside it, which is how you tell one svchost.exe from the others. sc.exe has a syntax quirk you will hit immediately: the space goes after the equals sign, not before. state= all works; state=all does not. sc qc <service> prints the service configuration including BINARY_PATH_NAME and the account it runs as — two fields Chapter 3 comes back to.
Permissions and attributes:
icacls "C:\Program Files\VendorApp"
attrib -h -s C:\Users\Public\notes.txticacls prints the ACL. The shorthand is dense but learnable: (F) full control, (M) modify, (RX) read and execute, (W) write, (OI)(CI) inherited by objects and containers beneath it.
Built-ins, operators and loops
Environment variables are how CMD stores state, and they are also a fast map of the machine:
set
echo %USERNAME% on %COMPUTERNAME%
echo %USERPROFILE%
set PATHset with no argument dumps every variable. set PATH prints every variable whose name starts with PATH — a prefix match, not an exact one. The ones worth memorising are %USERNAME%, %COMPUTERNAME%, %USERPROFILE%, %APPDATA%, %PROGRAMDATA%, %TEMP%, %WINDIR% and %LOGONSERVER%.
Operators chain commands and redirect their output:
whoami > C:\Users\Public\out.txt
systeminfo >> C:\Users\Public\out.txt
sc qc NoSuchService 2>nul
net user someone & net localgroup administrators
ping -n 1 dc01 && echo REACHABLE || echo DOWN> overwrites, >> appends. 2>nul throws away the error stream while leaving normal output intact. & runs the next command regardless; && runs it only if the previous one succeeded; || runs it only if the previous one failed. When you need a literal &, |, > or ^ inside an argument, escape it with a caret: ^&.
Finally, for /f — the loop that makes CMD usable for real work. It reads lines from a file, from a literal string, or from the output of another command, and splits each line into tokens:
for /f "skip=1 tokens=1,2 delims=," %a in ('tasklist /fo csv') do @echo %~a is PID %~btokens=1,2 captures the first two fields into %a and %b, delims=, sets the separator, skip=1 discards a header line, and %~a strips surrounding quotes. One rule catches many users: at an interactive prompt the variable is a single percent sign (%a); inside a .bat or .cmd file it must be doubled (%%a). Copying a working one-liner into a batch file without doubling is a common CMD bug.
On wmic. You will find wmic all over older Windows notes and cheat sheets. Microsoft has deprecated it, and it is being removed from Windows — on current builds it may be absent or present only as an optional feature. Do not build habits on it. Every wmic query in this workbook is written as Get-CimInstance instead, which queries the same WMI data through a supported interface.
Chapter 2 — PowerShell Basics
A modern, object-oriented shell.
The single idea that makes PowerShell click: the pipeline carries objects, not text. In CMD, tasklist | findstr chrome is string matching against a printed table — if the column widths change, your script breaks. In PowerShell, Get-Process emits System.Diagnostics.Process objects with real typed properties, and the next command in the pipeline receives those objects intact. You never parse; you select.
Know which PowerShell you are in:
$PSVersionTablepowershell.exe is Windows PowerShell 5.1 — shipped in the box on every supported Windows, and the version you can count on being present. pwsh.exe is PowerShell 7, cross-platform, installed separately, and absent on a default build. Write for 5.1 unless you have checked, because a script that needs 7 will simply not run on a host that only has 5.1.
Cmdlets and the pipeline
Cmdlets are named Verb-Noun from a controlled verb list, which means you can often guess a command before you look it up. Three cmdlets let you find everything else:
Get-Command -Noun Service
Get-Help Get-Service -Examples
Get-Service | Get-MemberGet-Command finds cmdlets by verb, noun or wildcard. Get-Help explains one — add -Examples for worked usage, or -Full for parameter detail. Get-Member is the important one: it lists the properties and methods of whatever is coming down the pipeline, so you stop guessing at property names.
Help may be empty on a fresh machine. PowerShell ships with stub help; the full text is downloaded by Update-Help, which needs an elevated prompt and internet access. On an isolated host, Get-Help <cmdlet> -Online and Get-Command <cmdlet> -Syntax are the fallbacks.
Now a real pipeline:
Get-Process |
Sort-Object -Property WorkingSet64 -Descending |
Select-Object -First 5 -Property Name, Id, WorkingSet64Illustrative output:
Name Id WorkingSet64
---- -- ------------
chrome 9128 841498624
Teams 4472 612368384
explorer 3216 198529024
svchost 1092 94371840
powershell 774 78643200Get-Process produced objects, Sort-Object sorted them on a numeric property rather than on a printed string, and Select-Object kept five rows and three fields. Swap WorkingSet64 for CPU and the same pipeline answers a different question with no reparsing.
Filtering uses Where-Object:
Get-Service | Where-Object { $_.Status -eq 'Running' } | Select-Object Name, DisplayName
Get-Service | Where-Object Status -eq 'Running'$_ is the current object in the pipeline. The second form is the simplified comparison syntax and reads better for a single condition; use the script-block form when you need more than one test.
Filter left, format right. Push filtering as far upstream as you can — Get-ChildItem -Filter '*.config' is handled by the provider and is far faster than fetching everything and discarding most of it with Where-Object. And put Format-Table or Format-List last: they emit formatting objects, not data, so anything downstream of a Format-* cmdlet receives something it cannot work with. If the next step is a file, use Export-Csv or ConvertTo-Json, never Format-Table.
Aliases exist for interactive speed — gci, ls and dir all resolve to Get-ChildItem, select to Select-Object. Use them at the prompt; in a script write the full cmdlet name, because aliases can be redefined and some do not exist on non-Windows PowerShell 7.
Variables and objects
$target = 'WS-0142'
[int]$max = 5
$services = Get-Service -ComputerName $target -ErrorAction SilentlyContinue
$env:USERNAME
$env:COMPUTERNAMEVariables start with $ and hold objects, not strings — $services above is a collection you can sort, count and index. A type accelerator like [int] constrains it. Environment variables live in their own drive and are reached as $env:NAME.
Strings interpolate in double quotes and do not in single quotes, which is worth internalising early:
$user = 'jsmith'
Write-Output "user is $user" # user is jsmith
Write-Output 'user is $user' # user is $user
Write-Output "profile: $($env:USERPROFILE)"The $( ) subexpression embeds anything more complex than a bare variable: "$($proc.Name)" works, while "$proc.Name" stringifies the object and then appends the literal text .Name.
Three automatic variables you will use constantly: $? is True if the last command succeeded, $LASTEXITCODE holds the exit code of the last native executable (not of a cmdlet), and $Error[0] is the most recent error.
Scripts
A script is a .ps1 file. Turning a one-liner into one is mostly about naming the inputs:
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$OutputPath,
[int]$MinPort = 1
)
Write-Verbose "Collecting listeners on $env:COMPUTERNAME"
try {
$rows = Get-NetTCPConnection -State Listen -ErrorAction Stop |
Where-Object { $_.LocalPort -ge $MinPort } |
Select-Object LocalAddress, LocalPort, OwningProcess,
@{ Name = 'Process'
Expression = { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName } }
}
catch {
Write-Error "Collection failed: $($_.Exception.Message)"
exit 1
}
$rows | Sort-Object LocalPort | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Output "listeners written: $($rows.Count) -> $OutputPath"
exit 0Three things in there are the whole lesson. [CmdletBinding()] with a param block gives you -Verbose, tab completion and mandatory-parameter prompting for free. The @{ Name = ...; Expression = ... } hash table is a calculated property — it adds a column computed per object, which is how you join two sources without a database. And -ErrorAction Stop is what makes try/catch work at all: most cmdlet errors are non-terminating by default and sail straight past a catch block unless you promote them.
Running it depends on execution policy:
Get-ExecutionPolicy -List
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
.\Get-ListenerReport.ps1 -OutputPath .\listeners.csv -VerboseExecution policy is not a security control. Microsoft is explicit about this: it is a safety catch against running a script by accident, not a boundary against an attacker. powershell.exe -ExecutionPolicy Bypass -File x.ps1 sets it aside from the command line, and reading a script and piping it to the engine sets it aside without any switch at all. Treat it as a guardrail, not a defence — and never report "execution policy is Restricted" as a mitigating control in an assessment.
What you leave behind
PowerShell is heavily instrumented, and you should know that whether you are the one being audited or the one doing the auditing.
Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-PowerShell/Operational'; Id = 4104 } -MaxEvents 5 |
Select-Object TimeCreated, Id, LevelDisplayNameEvent ID 4104 is script block logging: when enabled by policy, it records the actual code the engine compiled, including code that was decoded or generated at runtime. 4103 is module/pipeline logging. Transcription (Start-Transcript) writes a full session log to a configured directory. All three are turned on through Group Policy under Administrative Templates → Windows Components → Windows PowerShell.
On top of that, PowerShell submits script content to AMSI, the Antimalware Scan Interface, so the installed antimalware product sees what the engine is about to run rather than only what is on disk. And a locked-down host may be running constrained language mode, which blocks arbitrary .NET method calls and type creation:
$ExecutionContext.SessionState.LanguageModeFullLanguage is unrestricted. ConstrainedLanguage means much of what you find in generic tooling will fail, and the fix is to write plain cmdlet-based PowerShell rather than to fight the mode.
Chapter 3 — Enumeration from the Console
Learning a host without a GUI.
You have a shell on a machine. Before anything else you need four answers: who am I, what is this box, what is running, and what can it reach. Work through them in that order and in roughly that priority — everything you decide later depends on the first one.
System and user info
Start with your own identity, because it bounds everything else:
whoami
whoami /priv
whoami /groupsIllustrative whoami /priv output for an ordinary user:
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ==================================== ========
SeShutdownPrivilege Shut down the system Disabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeUndockPrivilege Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
SeTimeZonePrivilege Change the time zone DisabledThat is an unremarkable list. The names worth stopping for when you do see them are SeImpersonatePrivilege, SeDebugPrivilege, SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege and SeLoadDriverPrivilege — each grants an ability that a standard user is not supposed to have, and each belongs in a report on its own.
whoami /groups shows group membership and, at the bottom, the mandatory integrity level. Medium Mandatory Level means the process is not elevated even if the account is an administrator; High Mandatory Level means it is. That distinction explains most "access denied even though I'm an admin" confusion on Windows.
Then the machine:
hostname
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" /C:"Domain"Illustrative:
OS Name: Microsoft Windows 10 Enterprise
OS Version: 10.0.19045 N/A Build 19045
System Type: x64-based PC
Domain: corp.example.comsysteminfo is slow but answers a lot at once — build, install date, boot time, domain, logon server, hotfixes and network cards. The PowerShell equivalents are easier to filter:
Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object Caption, Version, BuildNumber, InstallDate, LastBootUpTime
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10Accounts and local groups:
net user
net user jsmith
net localgroup
net localgroup administrators
net accountsGet-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet
Get-LocalGroupMember -Group 'Administrators'net accounts prints the local password and lockout policy — minimum length, maximum age, lockout threshold. On a domain-joined machine run it on a domain controller, or via net accounts /domain, to get the domain policy rather than the local one.
Running code and things that start automatically:
Get-Process | Select-Object Name, Id, Path | Sort-Object Name
Get-Service | Where-Object Status -eq 'Running' | Select-Object Name, DisplayName, StartType
Get-ScheduledTask | Where-Object State -ne 'Disabled' |
Select-Object TaskPath, TaskName, Stateschtasks /query /fo LIST /v
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"Scheduled tasks and the Run keys are where persistence lives: what you check on an incident, and what you check for weak permissions on an assessment.
Network info
ipconfig /all
route print
arp -a
netstat -ano
netstat -ano | findstr LISTENINGnetstat -ano gives you every connection with the owning PID — the -b switch adds the executable name but requires an elevated prompt. arp -a shows hosts this machine has recently talked to on the local segment, which is a free, entirely passive list of neighbours.
The PowerShell equivalents return objects, so they compose:
Get-NetIPConfiguration
Get-NetTCPConnection -State Listen | Sort-Object LocalPort
Get-NetRoute -AddressFamily IPv4 | Select-Object DestinationPrefix, NextHop, RouteMetric
Get-NetNeighbor -AddressFamily IPv4 | Where-Object State -ne 'Unreachable'
Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundActionFor reachability testing, Test-NetConnection replaces the old habit of using telnet to poke a port — and telnet is not installed by default anyway:
Test-NetConnection -ComputerName fileserver01 -Port 445
Test-NetConnection -ComputerName 10.10.20.15 -Port 3389 -InformationLevel Quiet-InformationLevel Quiet reduces the result to True or False, which is what you want inside a loop.
Domain context, using only tools guaranteed to be present:
$env:USERDNSDOMAIN
$env:LOGONSERVER
Resolve-DnsName -Name "_ldap._tcp.dc._msdcs.$env:USERDNSDOMAIN" -Type SRV
nltest /dclist:$env:USERDNSDOMAINThe SRV lookup is how a Windows client itself finds domain controllers, so it works from any domain-joined host with DNS. nltest is present on many builds but not guaranteed on every client edition — if it is missing, the SRV query has already given you the answer. The Get-AD* cmdlets come from RSAT and are absent unless someone installed the tools, so do not plan around them.
net view is unreliable now. Older material recommends net view /domain to list machines. It depended on the Computer Browser service and SMBv1, both disabled or removed on current Windows, so a blank result tells you nothing about the network. Use DNS and directory queries instead.
Useful one-liners
These are the ones worth keeping. Each is a small report rather than a fact.
Listening ports with the process that owns them — the join netstat cannot do:
Get-NetTCPConnection -State Listen |
Select-Object LocalAddress, LocalPort, OwningProcess,
@{ Name = 'Process'
Expression = { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName } } |
Sort-Object LocalPortIllustrative output:
LocalAddress LocalPort OwningProcess Process
------------ --------- ------------- -------
0.0.0.0 135 1092 svchost
0.0.0.0 445 4 System
0.0.0.0 3389 1544 svchost
127.0.0.1 49670 3216 sqlservrPort 445 owned by PID 4 (System) is normal on Windows — SMB is served by the kernel, not by a user-mode process. A service listening only on 127.0.0.1 is reachable from this host and not from the network, which changes how you rate it.
Credentials left in configuration files — grep the filesystem:
Get-ChildItem -Path C:\inetpub, C:\Scripts -Recurse -Include *.config, *.xml, *.ini, *.ps1 -ErrorAction SilentlyContinue |
Select-String -Pattern 'password\s*=', 'pwd\s*=', 'connectionString' |
Select-Object Path, LineNumber, LineNote that -Include only filters when the path is wildcarded or -Recurse is used, and -ErrorAction SilentlyContinue is there because a non-admin will hit directories they cannot read. The CMD equivalent when PowerShell is unavailable is findstr /s /i /m /c:"password" *.config.
Stored Windows credentials and current Kerberos tickets:
cmdkey /list
klistService binaries with unquoted paths — a classic local privilege escalation finding when the path contains a space and an intervening directory is writable:
Get-CimInstance -ClassName Win32_Service |
Where-Object { $_.PathName -and $_.PathName -notmatch '^\s*"' -and $_.PathName -match '\s' } |
Select-Object Name, StartMode, StartName, PathNameTreat that output as candidates, not findings. It also matches perfectly safe entries where the space is in the arguments rather than the path — svchost.exe -k netsvcs is the obvious one. Confirm by eye, then check whether you can actually write to a directory earlier in the path:
icacls "C:\Program Files\VendorApp"Without write access on an intervening directory, an unquoted path is a hygiene note, not an escalation. Reporting it as exploitable without that second check is how a report loses credibility.
Two registry values that are worth one command:
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevatedAlwaysInstallElevated only matters when it is set to 1 in both hives; either one alone does nothing. If the value is absent you will get an error, which is the normal and healthy result.
Applied policy and sessions:
gpresult /r
query userRecent successful logons, when you have the rights to read the Security log:
Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4624 } -MaxEvents 20 |
Select-Object TimeCreated, Id, @{ Name = 'User'; Expression = { $_.Properties[5].Value } }Event 4624 is a successful logon. The property index for the account name is stable for that event but is not a general rule across event IDs — for anything unfamiliar, print one full record with Format-List * first and confirm which field you want before you build a report on it.
Capture your work
Whatever you run, capture it. Two options, both built in:
Start-Transcript -Path "$env:USERPROFILE\Desktop\enum-$(Get-Date -Format 'yyyyMMdd-HHmmss').txt"
# ... run your enumeration ...
Stop-TranscriptGet-Service | Export-Csv -Path .\services.csv -NoTypeInformation
Get-Process | ConvertTo-Json -Depth 2 | Set-Content -Path .\processes.jsonA transcript is the narrative — every command and its output, timestamped, which is what a client asks for when they want to know what you touched. CSV and JSON are the data. Produce both: notes reconstructed from memory after the fact are the least reliable artefact in this trade.
Keep going. Work through each chapter in order, then apply what you learned in the matching labs. The habit that carries over is the one from Chapter 2 — describe the object before you filter it. Run Get-Member on anything new, and you no longer need to guess property names.
Sign in to track progress and send feedback.