Windows Command Line (CMD) Cheat Sheet

Quick Reference

Open CMD as Admin
Win+X → Terminal (Admin)
Get help for any command
command /?
Pipe output
command1 | command2
Redirect to file
> overwrite  ·  >> append
Suppress all output
command > nul 2>&1
Environment variable
%VARIABLE_NAME%
Clear screen
cls
Script directory path
%~dp0

Operators & Redirection

OperatorMeaning
|Pipe stdout to next command
>Redirect stdout to file (overwrite)
>>Redirect stdout to file (append)
2>Redirect stderr to file
2>&1Merge stderr into stdout
OperatorMeaning
&Run second command regardless of first
&&Run second only if first succeeded
||Run second only if first failed
^Escape special characters
( )Group commands into a block
Tip: Use command /? for built-in help on any command — for example robocopy /? or netsh /?.

Navigation & Filesystem

Categories

CommandWhat It Does
cd C:\WindowsChange to directory
cd ..Go up one level
cd \Go to root of current drive
D:Switch to drive D
CommandWhat It Does
cd /d D:\FolderChange drive and directory in one step
pushd \\server\shareSave current dir and navigate (supports UNC)
popdReturn to directory saved by pushd
cdPrint current directory path
Spaces in paths: Always wrap paths with spaces in double quotes: cd "C:\Program Files"
CommandWhat It Does
dirList files and folders
dir /aShow hidden and system files
dir /s *.logSearch recursively for .log files
dir /bBare format — names only
dir /o:sSort by size
CommandWhat It Does
dir /o:dSort by date
treeDisplay folder structure as tree
tree /fShow tree including files
where notepad.exeFind full path of an executable
find "text" file.txtSearch for text inside a file
CommandWhat It Does
copy file.txt D:\Backup\Copy file to destination
copy *.txt D:\Backup\Copy all .txt files
move file.txt D:\Archive\Move file
ren old.txt new.txtRename file
del file.txtDelete file
del /s /q *.tmpDelete .tmp files recursively, no confirm
CommandWhat It Does
type file.txtPrint file contents
more file.txtDisplay file page by page
echo text > file.txtWrite text to new file
echo text >> file.txtAppend text to file
fc file1.txt file2.txtCompare two files line by line
comp file1 file2Binary file comparison
CommandWhat It Does
mkdir logsCreate directory
mkdir "My Folder"Create folder with spaces
mkdir C:\A\B\CCreate nested dirs in one step
rmdir logsRemove empty directory
rmdir /s /q logsRemove folder and all contents
CommandWhat It Does
xcopy C:\Src D:\Dst /s /e /iCopy tree including empty subfolders
robocopy C:\Src D:\Dst /eRobust copy with subdirectories
robocopy C:\Src D:\Dst /mirMirror — deletes files not in source
robocopy C:\Src D:\Dst /z /log:out.logResume on failure + write log
robocopy C:\Src D:\Dst /e /xf *.tmpCopy tree, exclude .tmp files
CommandWhat It Does
attrib file.txtShow file attributes (R, H, S, A)
attrib +h file.txtSet hidden attribute
attrib -r file.txtRemove read-only attribute
attrib +r +h /s /d C:\FolderApply attributes recursively
CommandWhat It Does
mklink link.txt target.txtCreate symbolic link to file
mklink /d LinkDir TargetDirCreate symbolic link to directory
mklink /j LinkDir TargetDirCreate junction (no admin required)
mklink /h link.txt target.txtCreate hard link

Processes & Services

Processes

CommandWhat It Does
tasklistList all running processes
tasklist /fi "imagename eq chrome.exe"Filter by process name
tasklist /fi "status eq not responding"Find hung processes
tasklist /svcShow services per svchost process
tasklist /m kernel32.dllFind processes using a DLL
start notepad.exeStart a program
CommandWhat It Does
taskkill /im notepad.exeKill process by name
taskkill /pid 1234Kill process by PID
taskkill /im chrome.exe /fForce kill process
taskkill /im chrome.exe /f /tForce kill process tree
start "" "C:\Program Files\app.exe"Start app with space in path
start /wait setup.exeStart and wait for it to finish

Services

CommandWhat It Does
sc queryList all services and state
sc query SpoolerQuery specific service status
sc start SpoolerStart a service
sc stop SpoolerStop a service
sc config Spooler start= autoSet service to auto-start
CommandWhat It Does
sc config Spooler start= disabledDisable a service
net startList running services
net start "Print Spooler"Start service by display name
net stop "Print Spooler"Stop service by display name
sc query type= allList all services including drivers
sc vs net: sc uses the internal service name (e.g. Spooler). net start/stop uses the display name (e.g. "Print Spooler"). Note the space after start= in sc config — it is required.

Networking

CommandWhat It Does
ipconfigShow IP addresses for all adapters
ipconfig /allFull details: MAC, DNS, DHCP lease
ipconfig /flushdnsFlush DNS resolver cache
ipconfig /releaseRelease DHCP lease
ipconfig /renewRenew DHCP lease
ping google.comTest connectivity (4 packets)
ping -t 8.8.8.8Continuous ping (Ctrl+C to stop)
ping -n 10 8.8.8.8Ping with specific packet count
ping -a 192.168.1.1Resolve IP to hostname while pinging
tracert google.comTrace route to destination
tracert -d google.comTraceroute without DNS (faster)
pathping google.comPing + traceroute + packet loss stats
CommandWhat It Does
nslookup google.comDNS lookup for hostname
nslookup -type=MX google.comLook up MX records
nslookup google.com 8.8.8.8Query a specific DNS server
netstat -anAll connections and listening ports
netstat -bShow process name per connection (admin)
netstat -rnShow routing table
netstat -ano | find ":80"Find what is using port 80
arp -aShow ARP cache (IP to MAC)
arp -dClear ARP cache
route printShow full routing table
netsh wlan show profilesList saved Wi-Fi networks
netsh wlan show profile "WiFi" key=clearShow saved Wi-Fi password
netstat -b requires admin: Without elevation it returns “The operation requires elevation”. Run CMD as Administrator to see process names per connection.

System Information

CommandWhat It Does
systeminfoFull system info: OS, RAM, hotfixes
systeminfo | find "OS Name"Windows version only
systeminfo | find "Total Physical Memory"Total RAM
systeminfo | find "System Boot Time"Last boot time
hostnameDisplay computer name
verDisplay Windows version string
winverOpen Windows version info dialog
setList all environment variables
echo %COMPUTERNAME%Computer name
echo %USERNAME%Current user name
echo %USERPROFILE%Current user’s home directory
echo %APPDATA%AppData\Roaming path
CommandWhat It Does
wmic os get caption,version,buildnumberOS name, version, build
wmic cpu get name,numberofcoresCPU name and core count
wmic memorychip get capacityRAM per DIMM slot in bytes
wmic bios get manufacturer,smbiosbiosversionBIOS info
wmic diskdrive get model,sizePhysical disk model and size
wmic logicaldisk get caption,freespace,sizeDrive free space and total size
wmic product get name,versionList installed software
wmic qfe list briefList installed Windows updates (hotfixes)
date /tDisplay current date
time /tDisplay current time
echo %DATE% %TIME%Date and time in one line
net statistics workstationUptime and network stats

Users & Permissions

CommandWhat It Does
net userList all local user accounts
net user usernameShow details for a specific user
net user username pass /addCreate a new local user
net user username newpassChange user password
net user username /active:noDisable a user account
net user username /deleteDelete a user account
whoamiShow current user name
whoami /groupsList current user’s group memberships
CommandWhat It Does
net localgroupList all local groups
net localgroup AdministratorsShow Administrators group members
net localgroup Administrators user /addAdd user to Administrators
net localgroup Administrators user /deleteRemove user from Administrators
whoami /privList current user’s privileges
runas /user:DOMAIN\admin cmd.exeRun CMD as another user
net accountsShow password and lockout policy
net sessionList active network sessions (admin)
CommandWhat It Does
icacls C:\FolderShow NTFS permissions
icacls file.txt /grant "User:(R)"Grant read permission
icacls file.txt /grant "Users:(F)"Grant full control
icacls file.txt /deny "User:(W)"Explicitly deny write access
CommandWhat It Does
icacls C:\Folder /grant "User:(OI)(CI)(M)"Modify on folder + subfolders + files
icacls file.txt /remove "User"Remove all permissions for a user
icacls C:\Folder /reset /tReset to inherited defaults (recursive)
icacls C:\Folder /save perms.txt /tExport permissions to file
FlagPermission Level
FFull control
MModify (read, write, execute, delete)
RXRead and execute
RRead only
WWrite only
FlagInheritance
(OI)Object inherit — applies to files in folder
(CI)Container inherit — applies to subfolders
(IO)Inherit only — not applied to the folder itself
(NP)No propagate — do not inherit further down
(I)Inherited from parent container

Disk & Storage

CommandWhat It Does
chkdsk C:Check disk for errors (read-only)
chkdsk C: /fFix file system errors
chkdsk C: /rFind bad sectors + recover data
fsutil volume diskfree C:Show free space for a volume
fsutil file createnew test.bin 1073741824Create a 1 GB test file
vol C:Show volume label and serial number
CommandWhat It Does
label C: NewLabelChange volume label
subst Z: "C:\Long\Path"Map folder to virtual drive letter
subst Z: /dRemove virtual drive mapping
substList all active virtual drive mappings
defrag C: /u /vDefragment drive with progress output
diskpartOpen diskpart interactive shell (admin)

Diskpart commands (run inside diskpart shell)

CommandWhat It Does
list diskList all physical disks
select disk 1Select disk 1
list partitionList partitions on selected disk
list volumeList all volumes
select volume 3Select volume 3
CommandWhat It Does
assign letter=ZAssign drive letter to selected volume
remove letter=ZRemove drive letter
online diskBring an offline disk online
attributes disk clear readonlyRemove read-only flag from disk
exitExit diskpart
Diskpart is destructive: No undo. Always double-check select disk before any operation. Selecting the wrong disk and cleaning it permanently destroys all data.

Registry

CommandWhat It Does
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersionRead a registry key
reg query HKCU\Software /f "chrome" /sSearch for pattern recursively
reg add HKCU\Software\MyApp /v Setting /t REG_SZ /d "value"Add or update a string value
reg add HKCU\Software\MyApp /v Count /t REG_DWORD /d 1Add a DWORD value
reg delete HKCU\Software\MyApp /v Setting /fDelete a value (no confirm)
CommandWhat It Does
reg delete HKCU\Software\MyApp /fDelete entire key and subkeys
reg export HKCU\Software\MyApp backup.regExport key to .reg file
reg import backup.regImport a .reg file
reg copy HKCU\Software\Src HKCU\Software\Dst /sCopy key including subkeys
regeditOpen Registry Editor GUI

Registry Hives

AbbreviationFull Name & Purpose
HKLMHKEY_LOCAL_MACHINE — system-wide settings
HKCUHKEY_CURRENT_USER — current user settings
HKCRHKEY_CLASSES_ROOT — file associations, COM
AbbreviationFull Name & Purpose
HKUHKEY_USERS — all user profiles loaded
HKCCHKEY_CURRENT_CONFIG — hardware profile
REG_SZ / REG_DWORD / REG_BINARYCommon value types: string / int / raw
Always export before editing: reg export HKCU\Software\MyApp backup.reg — there is no undo for deleted keys.

Event Logs & Diagnostics

wevtutil — Event Logs

CommandWhat It Does
wevtutil elList all available event logs
wevtutil gl SystemGet configuration of a log
wevtutil qe System /c:20 /f:text /rd:trueLast 20 System events as text
wevtutil cl ApplicationClear Application event log (admin)
CommandWhat It Does
wevtutil qe Security /q:"*[System[EventID=4625]]" /c:10 /f:text /rd:trueLast 10 failed logons (ID 4625)
wevtutil epl System C:\backup\system.evtxExport log to file
eventvwrOpen Event Viewer GUI
eventvwr /l:C:\backup\system.evtxOpen a saved .evtx file

System Diagnostics

CommandWhat It Does
sfc /scannowScan and repair system files (admin)
sfc /verifyonlyScan only, no repair
DISM /Online /Cleanup-Image /CheckHealthQuick check for component store issues
DISM /Online /Cleanup-Image /ScanHealthFull component store scan
DISM /Online /Cleanup-Image /RestoreHealthRepair using Windows Update
CommandWhat It Does
gpresult /rShow applied Group Policy (user + computer)
gpresult /h gpreport.htmlGenerate full GPO report as HTML
gpupdate /forceForce immediate Group Policy refresh
msconfigSystem Config: startup, services, boot
perfmon /reportGenerate performance diagnostic report

Batch Scripting Essentials

SyntaxMeaning
set name=valueDefine a variable (no spaces around =)
echo %name%Print variable value
set /p name=Enter value: Prompt user for input
set /a result=5+3Arithmetic expression
setlocal enabledelayedexpansionEnable !var! inside blocks
echo !name!Delayed expansion (inside for/if blocks)
SyntaxMeaning
@echo offSuppress command echoing
echo.Print a blank line
pauseWait for keypress
rem This is a commentComment line
:: This is a commentAlternative comment (faster)
title My ScriptSet CMD window title
SyntaxMeaning
if "%1"=="" goto usageCheck if argument is empty
if exist file.txt echo foundCheck if file exists
if not exist file.txt goto endJump if file does not exist
if /i "%var%"=="yes"Case-insensitive string compare
if %ERRORLEVEL% neq 0 goto failCheck last exit code
SyntaxMeaning
goto labelJump to a label
:labelDefine a jump target
call :subroutineCall sub-routine and return
call other.bat arg1Call another script
exit /b 0Exit with code (0=success, 1=error)
ERRORLEVEL: Use if %ERRORLEVEL% neq 0 rather than if errorlevel 1 — the latter is true for any value ≥ 1 and can cause unexpected behavior.
SyntaxMeaning
for %%f in (*.txt) do echo %%fLoop over files matching pattern
for /r C:\Folder %%f in (*.log) do del "%%f"Recursive loop over files
for /l %%i in (1,1,10) do echo %%iNumeric loop 1 to 10, step 1
SyntaxMeaning
for /f "tokens=1,2" %%a in (file.txt) do ...Parse lines, split into tokens
for /f "delims=," %%a in (data.csv) do ...Parse CSV with comma delimiter
for /d %%d in (C:\*) do echo %%dLoop over directories only
%% vs %: Use %%f inside .bat files, use %f when typing directly in CMD interactively.
SyntaxMeaning
%1 %2 %3Script arguments by position
%0The script name itself
%*All arguments as a single string
shiftShift arguments: %2 becomes %1, etc.
SyntaxMeaning
%~f1Argument 1 expanded to full path
%~d1Drive letter only (e.g. C:)
%~p1Path only (without filename)
%~dp0Directory of the script itself

CMD vs PowerShell: When to Use Which

TaskUse CMDUse PowerShell
Quick one-liner✓ Often shorter syntaxMore verbose but precise
Robust file copyrobocopy is nativePossible but more complex
Simple batch scripts✓ .bat files run everywhereExecution policy can block .ps1
Managing servicessc / net work fine✓ Richer output, pipeline support
Filtering & sorting outputText parsing with find, findstr✓ Real objects, native filtering
Remoting to other machinesLimited (psexec, WMI)✓ Built-in PSRemoting
Active DirectoryBasic (net user only)✓ Full AD module
Error handlingERRORLEVEL only✓ try/catch, exceptions
Registry editingreg command is quickAlso possible via PSDrive
Compatibility (old systems)✓ Works back to Windows XPRequires PS version check
General rule: Use CMD for quick tasks and scripts that need to run everywhere without configuration. Use PowerShell for anything involving filtering, automation, or Windows APIs. For new scripts, PowerShell 7 is the modern standard.

FAQ

How do I run CMD as Administrator?
Three ways: (1) Press Win+X and choose Terminal (Admin). (2) Search for cmd in Start, right-click → Run as administrator. (3) From any CMD: runas /user:Administrator cmd.exe. Many commands silently fail or return “Access is denied” without elevation — when in doubt, run as admin.
How do I find which process is using a specific port?
Run as Administrator: netstat -ano | find ":80" — the PID is in the last column. Then: tasklist /fi "pid eq 1234" to get the process name. One-liner: for /f "tokens=5" %a in ('netstat -ano ^| find ":80" ^| find "LISTENING"') do tasklist /fi "pid eq %a"
What is the difference between xcopy and robocopy?
xcopy is older and simpler. robocopy supports resume on failure, bandwidth throttling (/ipg), mirroring (/mir), detailed logging, and preserving all NTFS attributes. For anything beyond a simple one-time copy, use robocopy. xcopy is considered legacy.
Why does my variable show as empty inside a for loop?
CMD expands %variables% when a line is parsed, not when it executes. Inside code blocks the entire block is parsed at once. The fix: add setlocal enabledelayedexpansion at the top of your script, then use !var! instead of %var% inside for and if blocks.
How do I suppress all output from a command?
To suppress stdout and stderr: command > nul 2>&1. Stderr only: command 2> nul. Stdout only: command > nul. To capture everything to a log instead: command >> script.log 2>&1
What is the difference between & and && when chaining commands?
& runs both commands regardless of result. && runs the second only if the first succeeded (ERRORLEVEL 0). || runs the second only if the first failed. Example: mkdir logs && cd logs changes into the directory only if mkdir succeeded.
How do I schedule a command to run automatically?
Use schtasks: schtasks /create /tn "MyTask" /tr "C:\Scripts\backup.bat" /sc daily /st 02:00 creates a task that runs daily at 2am. View existing tasks: schtasks /query /fo list. For a GUI: run taskschd.msc.