Windows Command Line and PowerShell
The commands every Windows technician should know, in Command Prompt and PowerShell, and how PowerShell's cmdlets and pipeline work.
Command Prompt, PowerShell and Windows Terminal
Graphical tools are fine for one PC and one change. The command line is faster for repeated work, works over remote connections, gives output you can paste into a ticket, and is the only way to reach some repair tools. Windows has two shells and one terminal:
-
Command Prompt
(
cmd.exe) is the classic Windows command-line interpreter, descended from MS-DOS (Microsoft Disk Operating System). It runs built-in commands such asdirandcopy, external programs such asipconfig.exe, and batch files (.bat,.cmd). Everything it passes between commands is text. -
PowerShell is Microsoft's
command shell and scripting language, built on .NET, whose
commands (cmdlets) work with objects instead of text. Windows
includes Windows PowerShell 5.1; the newer, cross-platform
PowerShell 7 (
pwsh) is a separate install. It runs most classic commands too, soipconfigandpingwork in both. - Windows Terminal is not a shell but the window around one: tabs, panes, copy and paste, fonts. In Windows 11 it is the default terminal, and it opens PowerShell or Command Prompt in tabs.
Command Prompt examples on this page are labeled
batch, PowerShell examples powershell.
Output marked "illustrative" shows what the command typically
prints; your names, numbers and addresses will differ.
Running as administrator
Even when you sign in with an administrator account, programs run
with standard rights until you approve elevation through User
Account Control (UAC). A prompt that can repair Windows must be
started elevated: right-click Terminal (or search for
cmd) and choose Run as administrator,
use Win+X > Terminal (Admin), or press
Ctrl+Shift+Enter on a search
result. The window title then starts with "Administrator:", and the
default folder is C:\Windows\system32 instead of your
profile folder.
Navigation and files
Command Prompt always has a current directory, shown in the prompt.
Paths are absolute (C:\Users\ana\Documents) or relative
to where you are (Documents\Invoices);
.. is the parent folder. Put paths with spaces in
double quotes.
cd C:\Users\ana\Documents
dir /a
md Invoices
cd ..
cd /d E:\Backup
-
cd(change directory) moves around;cd ..goes up one level,cd \to the root of the drive, andcd /d E:\Backupchanges drive and folder at once. TypingE:alone switches drive. -
dirlists a folder;/aincludes hidden and system files,/ssearches subfolders too. -
mdormkdircreates a folder;rdorrmdirremoves an empty one, andrd /s /qremoves a folder with everything in it, without asking. -
copycopies files,movemoves or renames them,renrenames,deldeletes,typeprints a text file. -
xcopycopies folder trees (/sfor subfolders,/eincluding empty ones);robocopyis its more robust successor.
robocopy
robocopy (robust file copy) is the tool for copying
large folder trees and for migrations: it retries after network
errors, keeps timestamps and attributes, skips files that are
already identical, and writes a summary at the end.
robocopy C:\Users\ana\Documents E:\Backup\Documents /E /R:3 /W:5 /LOG:C:\Temp\copy.log
/E copies all subfolders, including empty ones.
/R:3 /W:5 retries a failing file three times, five
seconds apart (the defaults are a million retries, 30 seconds
apart). /LOG writes the output to a file for the
ticket. And then there is /MIR, mirror, which is
/E plus /PURGE: it makes the destination
an exact copy of the source, which includes deleting whatever exists
only at the destination. This model shows what the two switches
would do when a user's Documents folder is copied to the root of a
USB (Universal Serial Bus) drive that already holds other files:
# File name -> (size in bytes, last modified) on each side
source = { # C:\Users\ana\Documents
"budget.xlsx": (48213, "2026-09-30 16:02"),
"notes.txt": (1204, "2026-09-12 09:14"),
"plan.docx": (30551, "2026-10-01 11:40"),
}
destination = { # E:\ (the whole USB drive)
"notes.txt": (1204, "2026-09-12 09:14"),
"plan.docx": (29870, "2026-09-02 10:05"),
"photos-2025.zip": (812004113, "2025-12-28 20:31"),
"tax-return.pdf": (220410, "2026-04-30 18:12"),
}
def plan(source, destination, mirror):
actions = []
for name in sorted(source):
if name not in destination:
actions.append(("COPY (new)", name))
elif source[name] != destination[name]:
actions.append(("COPY (changed)", name))
if mirror: # /MIR = /E plus /PURGE
for name in sorted(destination):
if name not in source:
actions.append(("DELETE", name))
return actions
for switch, mirror in (("/E", False), ("/MIR", True)):
print(f"robocopy C:\\Users\\ana\\Documents E:\\ {switch}")
for action, name in plan(source, destination, mirror):
print(f" {action:<15} {name}")
robocopy C:\Users\ana\Documents E:\ /E COPY (new) budget.xlsx COPY (changed) plan.docx robocopy C:\Users\ana\Documents E:\ /MIR COPY (new) budget.xlsx COPY (changed) plan.docx DELETE photos-2025.zip DELETE tax-return.pdf
Like robocopy, the model treats a file as changed when its size or
timestamp differs, and skips identical files
(notes.txt). With /MIR, the photos and the
tax return on the USB drive are deleted, because they are not in the
source. The same happens when source and destination are swapped by
accident: the mirror then "synchronizes" the user's folder with an
older backup.
Disk and system repair tools
Three tools repair different layers of a Windows installation, from the bottom up: the file system, the protected system files, and the store those files are repaired from. All three need an elevated prompt.
chkdsk
CHKDSK (Check Disk) is the Windows
command that checks a volume's file system for logical errors and,
with its repair switches, fixes them and scans for bad sectors.
Without switches it only reports. /f fixes file system
errors; /r also locates bad sectors and recovers
readable data from them (it includes /f and can take
hours on a large hard drive).
chkdsk C: /f /r
The type of the file system is NTFS. Cannot lock current drive. Chkdsk cannot run because the volume is in use by another process. Would you like to schedule this volume to be checked the next time the system restarts? (Y/N)
A volume in use, such as the system drive, cannot be repaired while
Windows runs from it. Answer Y and restart; the check
runs before Windows starts. On a failing drive, back up first:
/r puts a lot of load on a disk that may be dying. See
Storage for drive health.
sfc
System File Checker
(sfc) is the Windows tool that verifies protected
system files and replaces damaged or modified ones with correct
copies from the Windows component store. Use it when Windows behaves
strangely after a crash, a failed update or malware removal.
sfc /scannow
Beginning system scan. This process will take some time. Beginning verification phase of system scan. Verification 100% complete. Windows Resource Protection found corrupt files and successfully repaired them. For online repairs, details are included in the CBS log file located at windir\Logs\CBS\CBS.log. For example C:\Windows\Logs\CBS\CBS.log.
The other possible results are "did not find any integrity violations" (nothing wrong) and "found corrupt files but was unable to fix some of them". The last one usually means the component store itself is damaged, which is the job of Deployment Image Servicing and Management (DISM).
DISM
DISM services Windows images, including the running installation.
Its most-used command repairs the component store that
sfc copies from, downloading good files from Windows
Update:
DISM /Online /Cleanup-Image /RestoreHealth
Deployment Image Servicing and Management tool Version: 10.0.26100.1 Image Version: 10.0.26100.4652 [==========================100.0%==========================] The restore operation completed successfully. The operation completed successfully.
/Online means the running Windows (as opposed to an
offline image file). /CheckHealth and
/ScanHealth only check. Microsoft's recommended order
is DISM first, then sfc /scannow, so that sfc repairs
from a healthy store. When and how to use these in a real problem is
in OS Troubleshooting.
format and diskpart
format E: /FS:NTFS /Q /V:Backup formats volume E: with
NTFS (New Technology File System), quickly (/Q, which
skips the surface scan), with the label "Backup". Everything on the
volume is lost. diskpart is an interactive tool for
disks, partitions and volumes, more powerful than Disk Management
and just as destructive; it is covered in
Disks, Partitions and Volumes. With both, check the drive letter or disk number twice.
Network commands
The network commands are the same in both shells. Their output and how to read it are explained in Network Troubleshooting; here is the technician's short list:
-
ipconfigshows IP (Internet Protocol) addresses;/alladds MAC (media access control) addresses, DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name System) servers./releaseand/renewgive up and request a DHCP address;/flushdnsempties the DNS cache. -
pingtests whether a host answers (-tuntil stopped,-n 10for ten packets);tracertshows the routers on the way;pathpingcombines both and measures loss per hop. nslookupasks a DNS server to resolve a name.-
netstat -anolists all connections and listening ports (-a) with numeric addresses (-n) and the process ID that owns each (-o). -
net usemaps and removes network drives;net userlists and manages user accounts.
Command Prompt can pass text from one command to another with
|. Filtering netstat through
findstr answers "which program is listening on port
3389?", and tasklist turns the process ID into a name:
netstat -ano | findstr :3389
tasklist /fi "PID eq 1312"
TCP 0.0.0.0:3389 0.0.0.0:0 LISTENING 1312 TCP [::]:3389 [::]:0 LISTENING 1312 Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ svchost.exe 1312 Services 0 14,280 K
Port 3389 is Remote Desktop, served by a svchost.exe
process that hosts the Remote Desktop service. Mapping a drive looks
like this:
net use Z: \\fileserver\projects /persistent:yes
net use Z: /delete
Policy and system information
A handful of short commands answer the first questions of many tickets, and apply or check Group Policy (see Windows Essentials):
gpupdate /force
Updating policy... Computer Policy update has completed successfully. User Policy update has completed successfully.
-
gpupdate /forcereapplies all Group Policy settings now instead of waiting for the next background refresh. -
gpresult /rsummarizes which Group Policy Objects were applied to the computer and the user (run it elevated to see the computer part);gpresult /h report.htmlwrites a full report. -
shutdown /r /t 0restarts immediately;/sshuts down,/tsets the delay in seconds,/fcloses applications without asking,/acancels a pending shutdown, andshutdown /r /o /t 0restarts into the Windows Recovery Environment's advanced options. -
winveropens a window with the Windows version and build;hostnameprints the computer name;whoamiprints the signed-in account (whoami /groupsadds its group memberships).
hostname
whoami
HR-LAPTOP-07 corp\ana
Getting help
Nobody remembers every switch. In Command Prompt, add
/? to any command (robocopy /?,
shutdown /?), and help lists the built-in
commands. In PowerShell, Get-Help shows the
documentation of a cmdlet; -Examples jumps to worked
examples, and Update-Help (as administrator) downloads
the full help text, which is not installed by default.
Get-Command *service* finds cmdlets by name.
Get-Help Get-Service -Examples
PowerShell: cmdlets and the pipeline
Cmdlets
A cmdlet (pronounced "command-let") is
a built-in PowerShell command named in Verb-Noun form, such as
Get-Service, that returns .NET objects rather than
text. The verbs come from a fixed list (Get,
Set, New, Remove,
Start, Stop, Restart…), so
once you know Get-Service you can guess
Restart-Service and Stop-Process.
Parameters start with a dash: -Name,
-Path.
Get-Service -Name Spooler
Status Name DisplayName ------ ---- ----------- Running Spooler Print Spooler
The print spooler is a classic help-desk case: print jobs stuck in
the queue are often solved with
Restart-Service -Name Spooler in an elevated
PowerShell.
Objects, not text
In Command Prompt, dir produces lines of text, and to
find the size of a file you have to cut it out of that text. In
PowerShell, Get-ChildItem produces file and folder
objects, each with properties such as Name,
Length (size in bytes) and LastWriteTime.
The table you see is only how PowerShell displays those objects at
the end.
Get-ChildItem C:\Users\ana\Documents -Filter *.docx
Directory: C:\Users\ana\Documents Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 10/1/2026 11:40 AM 30551 plan.docx -a---- 9/18/2026 2:15 PM 84210 report.docx
The pipeline
The PowerShell pipeline
(|) passes the objects that one cmdlet outputs, one by
one, as input to the next cmdlet. Because they are objects, the next
cmdlet can sort, filter or select by property name, without any text
parsing. The five processes that used the most CPU (central
processing unit) time:
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 -Property Name, Id, CPU
Name Id CPU ---- -- --- msedge 8812 1543.203125 Teams 6120 902.453125 explorer 4476 310.84375 OneDrive 7204 95.28125 svchost 1312 41.0625
CPU is the processor time in seconds that each process
has used since it started, not a current percentage. Two more
pipeline patterns you will use often: filtering with
Where-Object, and exporting with
Export-Csv for a report.
Get-Service | Where-Object Status -eq 'Stopped'
Get-Service | Export-Csv C:\Temp\services.csv -NoTypeInformation
Aliases
To make the switch easier, PowerShell defines aliases: short names
for cmdlets. dir and ls both run
Get-ChildItem, cd runs
Set-Location, copy and cp run
Copy-Item, del and rm run
Remove-Item, cls runs
Clear-Host. Get-Alias lists them all.
Execution policy
PowerShell scripts are files with the .ps1 extension.
On Windows client editions the default execution policy is
Restricted: interactive commands work, but scripts do
not run. A common setting is RemoteSigned, which runs
local scripts but requires a digital signature on scripts downloaded
from the internet:
Get-ExecutionPolicy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
The execution policy is a safety feature against running scripts by accident, not a security boundary: a user can bypass it. In organizations it is usually set by Group Policy. Never lower it because a web page tells you to paste a command: running copy-and-paste commands from untrusted sources is a known way to install malware.
Environment variables
An environment variable is a named value that the operating system passes to every program it starts, used for settings such as the user's profile folder or the folders searched for commands. Some exist on every Windows PC:
-
USERPROFILE: the user's profile folder, such asC:\Users\ana. -
APPDATA,LOCALAPPDATA,TEMP: where applications keep settings, caches and temporary files. -
SystemRoot(orwindir): the Windows folder, usuallyC:\Windows. -
COMPUTERNAME,USERNAME: the obvious. -
PATH: the list of folders searched for a program when you type only its name.
The syntax differs per shell: %NAME% in Command Prompt,
$env:NAME in PowerShell. File Explorer's address bar
accepts the Command Prompt form, so %appdata% opens the
roaming AppData folder.
echo %USERPROFILE%
echo %PATH%
$env:USERPROFILE
$env:PATH -split ';'
How PATH finds a command
When you type ping, Command Prompt first looks in the
current directory, then in each folder of PATH in
order, trying each extension listed in
PATHEXT (.COM, .EXE,
.BAT, .CMD and a few more). The first
match wins. PowerShell deliberately skips the current directory: to
run a script there you must type .\script.ps1. A model
of both searches:
PATHEXT = [".COM", ".EXE", ".BAT", ".CMD"]
PATH = [r"C:\Windows\system32", r"C:\Windows", r"C:\Tools"]
CURRENT = r"C:\Users\ana\Downloads"
files = {
r"C:\Users\ana\Downloads": ["ping.bat", "setup.exe"],
r"C:\Windows\system32": ["ipconfig.exe", "ping.exe", "robocopy.exe"],
r"C:\Windows": ["notepad.exe"],
r"C:\Tools": ["7z.exe"],
}
def find(command, search_current_first):
folders = ([CURRENT] if search_current_first else []) + PATH
for folder in folders:
present = {name.lower() for name in files.get(folder, [])}
for ext in PATHEXT:
if (command + ext).lower() in present:
return folder + "\\" + command + ext.lower()
return None
for command in ["ping", "7z", "notepad++"]:
for shell, current_first in (("cmd", True), ("PowerShell", False)):
found = find(command, current_first)
print(f"{shell:<10} {command:<9} -> {found or 'not found'}")
cmd ping -> C:\Users\ana\Downloads\ping.bat PowerShell ping -> C:\Windows\system32\ping.exe cmd 7z -> C:\Tools\7z.exe PowerShell 7z -> C:\Tools\7z.exe cmd notepad++ -> not found PowerShell notepad++ -> not found
Two lessons. A file called ping.bat in the current
folder wins over the real ping.exe in Command Prompt,
which is exactly why PowerShell refuses to search there. And a
program outside every PATH folder gives the familiar
"'notepad++' is not recognized as an internal or external command,
operable program or batch file." Either type the full path, or add
the program's folder to PATH.
Command reference
| Command | What it does | Example |
|---|---|---|
cd |
Change the current directory | cd /d E:\Backup |
dir |
List files and folders | dir /a /s *.pst |
md / rd |
Create / remove a directory | rd /s /q C:\Temp\old |
copy, move, del
|
Copy, move or delete files | del /q C:\Temp\*.tmp |
robocopy |
Copy folder trees robustly; mirror with care | robocopy D:\Data E:\Data /MIR /L |
chkdsk |
Check and repair a file system | chkdsk C: /f |
sfc |
Verify and repair protected system files | sfc /scannow |
DISM |
Repair the component store |
DISM /Online /Cleanup-Image /RestoreHealth
|
format |
Format a volume (erases it) | format E: /FS:NTFS /Q |
diskpart |
Manage disks, partitions and volumes | diskpart, then list disk |
ipconfig |
Show and renew IP configuration, flush DNS | ipconfig /flushdns |
ping, tracert,
pathping
|
Test reachability and the path | tracert www.example.com |
nslookup |
Query DNS | nslookup www.example.com |
netstat |
Connections, listening ports, owning process | netstat -ano |
net use |
Map or remove a network drive | net use Z: \\fileserver\projects |
net user |
List or manage user accounts | net user ana /domain |
gpupdate |
Reapply Group Policy | gpupdate /force |
gpresult |
Show applied Group Policy | gpresult /r |
shutdown |
Shut down, restart, log off | shutdown /r /t 0 |
winver, hostname,
whoami
|
Version, computer name, current account | whoami /groups |
Get-Help |
Documentation for a cmdlet | Get-Help Get-Process -Examples |
Get-Process, Get-Service |
Processes and services as objects | Get-Service -Name Spooler |
Get-ChildItem |
Files and folders as objects | Get-ChildItem -Recurse -Filter *.log |