The Windows Command Prompt (CMD) is a powerful tool that allows users to interact with their operating system through text-based commands. Whether you’re a beginner exploring CMD for the first time, an expert troubleshooting advanced issues, or just looking for utility-focused tasks, this guide has you covered.
In this guide, we will provide you with some of the most useful commands for the following:
- CMD Commands for Beginners
- CMD Commands for Experts
- CMD Commands for Utility
- CMD Commands for Troubleshooting
- CMD Commands for Students
- CMD Commands for Programmers
CMD Commands for Beginners
These commands are essential for users who are new to CMD and provide basic functionalities to help them navigate and perform simple tasks.
1. View Directory ‘dir‘
- Function: Displays the contents of the current directory.
- How to use: Type
dirand press Enter. Usedir /sto include subdirectories. - Use case: Quickly view files and folders in your current location.
Syntax: dir
2. Change Directories ‘cd’
- Function: Lets you navigate between folders.
- How to use: Type
cd [folder_name]to move into a directory. Usecd ..to go up one level. - Use case: Navigate to specific directories to manage files or execute commands
Syntax: cd [folder name]
3. Create a New Directory ‘mkdir’ or ‘md’
- Function: Allows you to create a new directory
- How to use: Type mkdir [file_name]– Here the new directory name is GFG
- Use case: When you need a new directory for any separate work, you may create a new directory
Syntax: mkdir [GFG]
4. Rename a File ‘ren’
- Function: Helps in renaming any file or directory.
- How to use: Type
renorrename [old_name] [new_name]and press Enter. - Use case: Discover new method of renaming file or any directory.
Syntax: ren xyz.txt newxyz.txt
5. Delete a File ‘del’
- Function: Lets you to remove one or more files
- How to use: Type del [file_name]– This will erase the provided file name
- Use case: This function allows you to erase any file if you’re unable to fetch
Syntax: del[file_name]
6. Close ‘exit’
- Function: Closes the Command Prompt window.
- How to use: Type
exitand press Enter. - Use case: Ends your session with CMD.
Syntax: exit
7. Clear Screen ‘cls’
- Function: Clears all text from the CMD window.
- How to use: Type
clsand press Enter. - Use case: Removes clutter after multiple commands
Syntax: cls
8. View Available Command ‘help’
- Function: Lists all available commands and their descriptions.
- How to use: Type
helpand press Enter. - Use case: Discover new commands and learn their functions.
Syntax: help
9. Display or Set the System time ‘time’
- Function: Lets you set the system time or display the current time.
- How to use: Type
time [new_time] and press Enter. - Use case: Allows the user to set their system’s time without additional navigation
Syntax: time [new_time]
10. Copy Files ‘copy’
- Function: Lists all available commands and their descriptions.
- How to use: Type
copy [source1] [destination2] and press Enter. - Use case: Discover new commands and learn their functions.
Syntax: copy file.txt Backup\
| Command | Description | Syntax | Example |
|---|---|---|---|
dir |
View the contents of a directory | dir |
dir C:\Users\Documents |
cd |
Change the current working directory | cd [directory_name] |
cd Downloads |
mkdir |
Create a new directory | mkdir [directory_name] |
mkdir NewProject |
ren |
Rename a file | ren [old_name] [new_name] |
ren draft.txt final.txt |
del |
Delete a file | del [file_name] |
del unwanted.txt |
exit |
Close the Command Prompt | exit |
exit |
cls |
Clear the Command Prompt screen | cls |
cls |
help |
View available CMD commands and their descriptions | help |
help |
time |
Display or set the system time | time |
time 14:30:00 |
copy |
Copy files from one location to another | copy [destination] |
copy report.docx D:\Backup\ |
CMD Commands for Experts
These commands are more advanced and suitable for users comfortable with troubleshooting and system management tasks.
1. System File Checker ‘sfc’
- Function: Scans and repairs corrupted system files.
- How to use: Type
sfc /scannowin CMD (run as administrator). - Use case: Fix system errors related to missing or corrupted files.
Syntax: sfc /scannow
2. Disk Error ‘chkdsk’
- Function: Scans the hard drive for bad sectors and file system errors.
- How to use: Type
chkdsk [drive letter]: /f(e.g.,chkdsk C: /f) in CMD. - Use case: Identify and fix disk issues.
Syntax: chkdsk C: /f
3. View Running Processor ‘tasklist’
- Function: Displays all running processes and their details.
- How to use: Type
tasklistto list processes. Usetasklist /fi "imagename eq [process name]"to filter. - Use case: Identify resource-heavy or unresponsive processes.
Syntax: tasklist /fi "imagename eq [process name]
4. Restart ‘shutdown’
- Function: Allows you to shut down or restart the computer via CMD.
- How to use:
- Shutdown:
shutdown /s /f /t [seconds]. - Restart:
shutdown /r /f /t [seconds].
- Shutdown:
- Use case: Automate shutdown or restart tasks
Syntax:
Shutdown: shutdown /s /f /t [seconds].
Restart: shutdown /r /f /t [seconds].
5. Network Statistics ‘netstat’
- Function: Displays active connections and listening ports.
- How to use: Type
netstatto view all active connections. - Use case: Diagnose network-related issues or monitor network activity.
Syntax: netstat
6. Kill a Running Process ‘taskkill’
- Function: Lets you terminate a process using its process ID (PID)
- How to use: Type
taskkill /[PID] /F to terminate - Use case: Can be helpful for terminating any dedicated PID.
Example (PID: 1124)
Syntax: taskkill /PID 11234 /F
7. View Saved Passwords ‘netsh wlan show profiles’
- Function: Retrieve the password of a saved Wi-Fi network.
- How to use: Type netsh wlan show profile name=”WiFi-Name” key=clear
- Use case: Discover new commands and learn their functions.
Example: netsh wlan show profile name="MyHomeWiFi" key=clear
| Command | Description | Syntax | Example |
|---|---|---|---|
sfc |
System File Checker – Scans and repairs system files | sfc /scannow |
sfc /scannow |
chkdsk |
Check Disk – Scans and fixes disk errors | chkdsk [drive]: /f /r |
chkdsk C: /f /r |
tasklist |
View running processes | tasklist |
tasklist |
shutdown |
Shutdown or restart the system | shutdown /r /t [seconds] |
shutdown /r /t 10 (Restart in 10 seconds) |
netstat |
View network statistics and active connections | netstat -a |
netstat -an (Show all connections numerically) |
taskkill |
Kill a running process using its process ID (PID) | taskkill /PID [PID] /F |
taskkill /PID 4567 /F (Kill process with ID 4567) |
netsh wlan show profiles |
View saved Wi-Fi network names | netsh wlan show profiles |
netsh wlan show profiles |
CMD Commands for Utility
These commands are focused on specific tasks and utilities to enhance productivity and system performance.
1. Network Configuration ‘ipconfig’
- Function: Displays IP address, subnet mask, and gateway information.
- How to use:
- Basic: Type
ipconfig. - Detailed: Type
ipconfig /all.
- Basic: Type
- Use case: Troubleshoot internet connectivity issues.
Syntax: ipconfig
2. Network Connectivity ‘ping’
- Function: Sends packets to test communication with another device or website.
- How to use: Type
ping[destination] - Use case: Check if a device or website is reachable.
Syntax: ping geeksforgeeks.org
3. System Information ‘systeminfo’
- Function: Displays detailed information about your computer.
- How to use: Type
systeminfo. - Use case: Quickly access system specifications for troubleshooting or reporting.
Syntax: systeminfo
4. Trace Route ‘tracert’
- Function: Shows the path packets take to reach a specific destination.
- How to use: Type
tracert[destination] - Use case: Identify network bottlenecks or connectivity issues.
Syntax: tracert geeksforgeeks.org
5. Manage Drives ‘diskpart’
- Function: Opens a command-line utility for managing disk partitions.
- How to use: Type
diskpartto enter the disk management interface. - Use case: Create, delete, or modify partitions on your drives.
Syntax: diskpart
6. Delete a Directory ‘rmdir’
- Function: Removes directory from the origin
- How to use: Type rmdir [directory_name] and press Enter.
- Use case: Discover new commands and learn their functions.
Example: GFG – Directory name
Syntax: rmdir GFG
7. View ‘rmdir’
- Function: Removes directory from the origin
- How to use: Type rmdir [directory_name] and press Enter.
- Use case: Discover new commands and learn their functions.
Example: GFG - Directory name
8. Manage User Account ‘net user’
- Function: To list all the user accounts
- How to use: Type net user and press Enter.
- Use case: Discover new commands and learn their functions.
Syntax: net user username password /add
9. View Startup Programs ‘wmic startup get caption,command’
- Function: To check what programs launch on startup.
- How to use: Type wmic startup get caption,command, and press Enter.
- Use case: Discover new commands and learn their functions.
Syntax: wmic startup get caption,command
| Command | Description | Syntax | Example |
|---|---|---|---|
ipconfig |
View network configuration, including IP address, subnet mask, and gateway | ipconfig |
ipconfig /all (Displays detailed network info) |
ping |
Test network connectivity by sending packets to a host | ping [host or IP] |
ping google.com (Check connection to Google) |
systeminfo |
Display detailed system information, including OS version, installed memory, and processor | systeminfo |
systeminfo |
tracert |
Trace the route packets take to a network destination | tracert [hostname or IP] |
tracert google.com (View network path to Google) |
diskpart |
Manage disk partitions, including creating, formatting, and deleting partitions | diskpart |
diskpart → list disk → select disk 1 → create partition primary |
rmdir |
Delete a directory (folder) | rmdir [directory_name] |
rmdir /s /q OldFolder (Delete a folder and its contents without confirmation) |
dir |
View contents of a directory | dir |
dir C:\Users\Documents (List files in a specific directory) |
net user |
Manage user accounts, including adding, modifying, or deleting users | net user |
net user John password123 /add (Create a new user account) |
wmic startup get caption,command |
View startup programs and their commands | wmic startup get caption,command |
wmic startup get caption,command |
CMD Commands for Troubleshooting
1. File Comparison ‘fc’
- Function: Compares two files and highlights differences.
- How to use: Type
fc [file1] [file2]to compare files. - Use case: Detect changes or errors in files
Syntax: fc 1 2
2. Advanced Network Diagnostics ‘pathping’
- Function: Combines
pingandtracertfunctionalities to provide detailed network path diagnostics. - How to use: Type
pathping[destination] - Use case: Troubleshoot complex network issues.
Syntax: pathping geeksforgeeks.org
3. Registry Editor ‘regedit’
- Function: Launches the Windows Registry Editor.
- How to use: Type
regeditto open the registry. - Use case: Modify registry keys for advanced configuration or troubleshooting.
Syntax: regedit
4. View MAC ‘getmac’
- Function: Displays the MAC address of your network adapter.
- How to use: Type
getmacto view the MAC address. - Use case: Identify your device’s hardware address for network configurations
Syntax: getmac
5. Power Configuration ‘powercfg’
- Function: Displays and manages power settings.
- How to use: Type
powercfg/[option] - Use case: Optimize power usage and troubleshoot battery issues.
Syntax: powercfg /energy for a detailed power usage report
6. Enable Boot Manager ‘bcdedit’
- Function: Used to modify boot configuration settings
- How to use: Type
bcdedit/ set current - Use case: Discover new commands and learn their functions.
Syntax: bcdedit /set {current} bootmenupolicy standard
7. Format a Drive ‘format’
- Function: To erase any specific drive.
- How to use: Type format [drive]: /FS:NTFS and press Enter.
- Use case: Discover new commands and learn their functions.
Syntax: format D: /FS:NTFS
| Command | Description | Syntax | Example |
|---|---|---|---|
fc |
Compare two files and highlight differences | fc [file1] [file2] |
fc file1.txt file2.txt (Compare two text files) |
pathping |
Perform advanced network diagnostics with packet loss details | pathping [destination] |
pathping google.com (Analyze network route to Google) |
regedit |
Open the Windows Registry Editor (GUI) | regedit |
regedit (Opens the registry editor – use with caution!) |
getmac |
Display the MAC (Media Access Control) address of your network adapters | getmac |
getmac /v /fo list (View MAC addresses in detailed format) |
powercfg |
Manage and analyze power configurations | powercfg /[option] |
powercfg /batteryreport (Generate a battery usage report) |
bcdedit |
Enable, disable, or modify Windows Boot Configuration | bcdedit /set {current} [option] |
bcdedit /set {current} bootmenupolicy standard (Enable boot menu in Windows 10/11) |
format |
Format a drive (erase all data) | format [drive]: /FS:[filesystem] |
format D: /FS:NTFS (Format drive D: with NTFS file system) |
CMD Commands for Students
Students can use these commands to manage files, perform simple calculations, and even help with tasks like coding and studying.
1. Calculator ‘calc’
- Function: Opens the Windows Calculator application.
- How to use: Type
calcand press Enter. - Use case: Quickly open the calculator for
Syntax: calc
CMD Commands for Programmers
Programmers often use CMD to automate tasks, compile code, and test network functionality. These commands can be especially useful for developers working in command-line environments.
1. Compile Java Code ‘javac’
- Function: Compiles Java source files into bytecode.
- How to use: Type
javac [file name].javato compile Java code. - Use case: Compile and test Java programs directly from the command line.
Syntax: javac
2. Version Control ‘git’
- Function: Interacts with Git repositories from the command line.
- How to use: Type
git [command] - Use case: Manage version control, clone repositories, or push commits from the command line.
Syntax: git clone [repository URL]
3. Execute Python Script ‘python’
- Function: Runs Python scripts in the command prompt.
- How to use: Type
python [script.py]to execute a Python program. - Use case: Test and run Python code directly in the command line.
Syntax: python [script.py]
4. Run Node.js Scripts ‘node’
- Function: Executes Node.js scripts.
- How to use: Type
node [script.js]to run a JavaScript file using Node.js. - Use case: Run backend scripts and test JavaScript programs in the command line.
Syntax: node [script.js]
5. Node Package Manager ‘npm’
- Function: Installs and manages JavaScript packages.
- How to use: Type
npm install [package]to install a package. - Use case: Manage dependencies and libraries in Node.js applications.
Syntax: npm install [package]
| Command | Description | Syntax | Example |
|---|---|---|---|
javac |
Compile Java source code into bytecode (.class files) | javac [filename].java |
javac HelloWorld.java (Compile a Java file) |
git |
Version control system for tracking changes in files | git [command] |
git clone https://github.com/user/repo.git (Clone a repository) |
python |
Execute a Python script or enter interactive mode | python [script.py] |
python script.py (Run a Python script) |
node |
Execute JavaScript code using Node.js | node [script.js] |
node app.js (Run a Node.js script) |
npm |
Manage Node.js packages and dependencies | npm [command] |
npm install express (Install the Express.js package) |
Bonus: CMD Tricks and Tips
To make CMD usage even more efficient, here are some bonus tips:
1. Save CMD Output to a File
Use the > operator to save the output of a command to a text file.
2. Open CMD in a Specific Directory
Instead of navigating manually, you can directly open CMD in a folder by typing cmd in the File Explorer’s address bar.
3. Use && for Multiple Commands
You can run multiple commands sequentially:
ipconfig && ping google.com
Conclusion
Mastering the most useful CMD commands in Windows can empower you to perform tasks more efficiently, troubleshoot problems, and gain deeper control over your system. By familiarizing yourself with these essential CMD commands, you’ll be better equipped to handle a variety of situations, from simple file management to advanced system configurations. Whether you’re a beginner or an experienced user, these commands are invaluable tools to have at your disposal.
This book describes and shows how to use the Microsoft-supplied command interpreter cmd.exe and the associated commands, and how to write Windows batch scripts for the interpreter. cmd.exe is the default interpreter on all Windows NT-based operating systems, including Windows XP, Windows 7 and Windows 10.
This book addresses 32-bit Windows commands applicable to modern versions of Windows based on the Windows NT environment. It does not address commands that are specific to DOS environments and to DOS-based operating systems, such as Windows 95, Windows 98, and Windows Me, whose Microsoft-supplied command interpreters are in fact DOS programs, not Win32 programs.
You can find out which version of Windows you are running using the VER command.
This book first describes using the Windows NT command interpreter, how it receives, parses, and processes commands from users. Then it describes various commands available.
To obtain an extensive list of Windows commands and their short summaries, open the command prompt on any Windows computer, and type help. To find out about a particular command, type the name of the command followed by «/?».
The subject of this book is also known as «batch programming», even though «batch» refers not only to batch files for MS DOS and Windows command interpreter. Other subject terms include «batch file programming», «batch file scripting», «Windows batch command», «Windows batch file», «Windows command line», «Windows command prompt», and «Windows shell scripting».
For Windows scripting, cmd.exe is a legacy technology; a modern equivalent is PowerShell, which is based on .NET and whose streams for pipelines are objects, not character (byte) streams. PowerShell capabilities vastly outstrip those of cmd.exe; PowerShell has the capabilities of a full programming language, including typed content of variables, floating-point arithmetic, big integers, GUI programming via .NET classes, etc. Nonetheless, cmd.exe is still useful for simple scripting and command-line interaction tasks, often offering shorter syntax and quicker startup time, and working with the character stream pipelining familiar from other operating systems. cmd.exe can be enhanced by commands known from other operating systems; see #Unix commands. Another alternative for scripting Windows is the popular Python with its pywin32 and wmi libraries; however, that requires installation.
The parsing of a command line into a sequence of commands is complex. There are four main components:
- Variable substitution: A command line is scanned for variable specifications, and any found are replaced with the contents of those variables.
- Quoting: Special characters can be quoted, to remove their special meanings.
- Syntax: Command lines are developed into a sequence of commands according to a syntax.
- Redirection: Redirection specifications are applied, and removed from the command line, before an individual command in a sequence is executed.
Command lines can contain variable specifications. These comprise a % character followed by a name, followed by a second % character unless the name is a digit in 0 … 9 or an asterisk *.
Variable specifications are replaced with values as follows:
- %varname%, such as %PATH% or %USERNAME%, is replaced with the value of the named environment variable. For example, %PATH% is replaced by the value of the PATH environment variable. The variable name match is case insensitive: %PATH% and %path% have the same effect.
- %n for 0 <= n <= 9, such as %0 or %9, is replaced with the value of the n-th parameter passed to the batch file when it was invoked, subject to any subsequent modifications by the SHIFT command. For example: %2 is replaced by the value of the second batch file parameter. In interactive use (outside of a batch), no substitution takes place for this case.
- %* is replaced with the values of all the command-line parameters except for %0, even those beyond index 9. SHIFT command has no impact on the result of %*. See also Command-line arguments. In interactive use (outside of a batch), no substitution takes place for this case.
Some variable names are not visible using SET command. Rather, they are made available for reading using the % notation. To find out about them, type «help set».
Special variable names and what they expand to:
| Name | Replacement Value Used |
|---|---|
| %CD% | The current directory, not ending in a slash character if it is not the root directory of the current drive. See also #CD. |
| %TIME% | The system time in HH:MM:SS.mm format unless regional settings dictate otherwise. See also #TIME. |
| %DATE% | The system date in a format specific to localization. See also #DATE. |
| %RANDOM% | A generated pseudorandom number between 0 and 32767. See also #Calculation. |
| %ERRORLEVEL% | The error level returned by the last executed command, or by the last called batch script. See also #Error level. |
| %CMDEXTVERSION% | The version number of the Command Processor Extensions currently used by cmd.exe. |
| %CMDCMDLINE% | The content of the command line used when the current cmd.exe was started. |
Links:
- Windows Environment Variables at ss64.com
- Command shell overview at TechNet / Microsoft Docs
You can prevent the special characters that control command syntax from having their special meanings as follows, except for the percent sign (%):
- You can surround a string containing a special character by quotation marks.
- You can place caret (^), an escape character, immediately before the special characters. In a command located after a pipe (|), you need to use three carets (^^^) for this to work.
The special characters that need quoting or escaping are usually <, >, |, &, and ^. In some circumstances, ! and \ may need to be escaped. A newline can be escaped using caret as well.
When you surround the string using quotation marks, they become part of the argument passed to the command invoked. By contrast, when you use caret as an escape character, the caret does not become part of the argument passed.
The percent sign (%) is a special case. On the command line, it does not need quoting or escaping unless two of them are used to indicate a variable, such as %OS%. But in a batch file, you have to use a double percent sign (%%) to yield a single percent sign (%). Enclosing the percent sign in quotation marks or preceding it with caret does not work.
Examples
- echo «Johnson & son»
- Echoes the complete string rather than splitting the command line at the & character. Quotes are echoed as well
- echo Johnson ^& son
- As above, but using caret before the special character ampersand. No quotes are echoed.
- echo Johnson & son
- Does not use an escape character and therefore, «son» is interpreted as a separate command, usually leading to an error message that command son is not found.
- echo A ^^ B
- Echoes A ^ B. Caret needs escaping as well or else it is interpreted as escaping a space.
- echo > NUL | echo A ^^^^ B
- Echoes A ^ B. When after a pipe, a caret used for escaping needs to be tripled to work; the fourth caret is the one being escaped.
- if 1 equ 1 ^
echo Equal &^
echo Indeed, equal- Echoes the two strings. The caret at the end of the line escapes the newlines, leading to the three lines being treated as if they were a single line. The space before the first caret is necessary or else 1 gets joined with the following echo to yield 1echo.
- attrib File^ 1.txt
- Does not show attributes of file named «File 1.txt» since escaping of space does not work. Using quotes, as in attrib «File 1.txt», works.
- echo The ratio was 47%.
- If run from a batch, the percent sign is ignored.
- echo The ratio was 47%%.
- If run from a batch, the percent sign is output once.
- set /a modulo=14%%3
- If run from a batch, sets modulo variable to 2, the remainder of dividing 14 by 3. Does not work with single %.
- for %%i in (1,2,3) do echo %%i
- If run from a batch, outputs 1, 2 and 3.
- echo %temp%
- Outputs the content of temp variable even if run from a batch file. Use of the percent sign in a batch to access environment variables and passed arguments needs no escaping.
- echo ^%temp^%
- Outputs literally %temp% when run from the command line.
- echo %%temp%%
- Outputs literally %temp% when run from a batch.
- echo //comment line | findstr \//
- Command FINDSTR uses backslash (\) for escaping. Unlike caret, this is internal to the command and unknown to the command shell.
Links:
- Syntax : Escape Characters, Delimiters and Quotes at ss64
- Command shell overview at Microsoft
- set at Microsoft
Command lines are developed into a sequence of commands according to a syntax. In that syntax, simple commands may be combined to form pipelines, which may in turn be combined to form compound commands, which finally may be turned into parenthesized commands.
A simple command is just a command name, a command tail, and some redirection specifications. An example of a simple command is dir *.txt > somefile.
A pipeline is several simple commands joined together with the «pipe» metacharacter—»|», also known as the «vertical bar». The standard output of the simple command preceding each vertical bar is connected to the standard input of the simple command following it, via a pipe. The command interpreter runs all of the simple commands in the pipeline in parallel. An example of a pipeline (comprising two simple commands) is dir *.txt | more.
A compound command is a set of pipelines separated by conjunctions. The pipelines are executed sequentially, one after the other, and the conjunction controls whether the command interpreter executes the next pipeline or not. An example of a compound command (comprising two pipelines, which themselves are just simple commands) is move file.txt file.bak && dir > file.txt.
The conjunctions:
- & — An unconditional conjunction. The next pipeline is always executed after the current one has completed executing.
- && — A positive conditional conjunction. The next pipeline is executed if the current one completes executing with a zero exit status.
- || — A negative conditional conjunction. The next pipeline is executed if the current one completes executing with a non-zero exit status.
A parenthesized command is a compound command enclosed in parentheses (i.e. ( and )). From the point of view of syntax, this turns a compound command into a simple command, whose overall output can be redirected.
For example: The command line ( pushd temp & dir & popd ) > somefile causes the standard output of the entire compound command ( pushd temp & dir & popd ) to be redirected to somefile.
Links:
- Conditional Execution at ss64.com
- Using parenthesis/brackets to group expressions at ss64.com
- Command shell overview at TechNet / Microsoft Docs
Redirection specifications are applied, and removed from the command line, before an individual command in a sequence is executed. Redirection specifications control where the standard input, standard output, and standard error file handles for a simple command point. They override any effects to those file handles that may have resulted from pipelining. (See the preceding section on command syntax.) Redirection signs > and >> can be prefixed with 1 for the standard output (same as no prefix) or 2 for the standard error.
The redirection specifications are:
- < filename
- Redirect standard input to read from the named file.
- > filename
- Redirect standard output to write to the named file, overwriting its previous contents.
- >> filename
- Redirect standard output to write to the named file, appending to the end of its previous contents.
- >&h
- Redirect to handle h, where handle is any of 0—standard input, 1—standard output, 2—standard error, and more.
- <&h
- Redirect from handle h.
Examples:
- dir *.txt >listing.log
- Redirects the output of the dir command to listing.log file.
- dir *.txt > listing.log
- As above; the space before the file name makes no difference. However, if you type this into the command window, auto-completion with tab after typing «> l» actually works, while it does not work with «>listing.log».
- dir *.txt 2>NUL
- Redirects errors of the dir command to nowhere.
- dir *.txt >>listing.log
- Redirects the output of the dir command to listing.log file, appending to the file. Thereby, the content of the file before the redirected command was executed does not get lost.
- dir *.txt >listing.log 2>&1
- Redirects the output of the dir command to listing.log file, along with the error messages.
- dir *.txt >listing.log 2>listing-errors.log
- Redirects the output of the dir command to listing.log file, and the error messages to listing-errors.log file.
- >myfile.txt echo Hello
- The redirection can precede the command.
- echo Hello & echo World >myfile.txt
- Only the 2nd echo gets redirected.
- (echo Hello & echo World) >myfile.txt
- Output of both echos gets redirected.
- type con >myfile.txt
- Redirects console input (con) to the file. Thus, allows multi-line user input terminated by user pressing Control + Z. See also #User input.
- (for %i in (1,2,3) do @echo %i) > myfile.txt
- Redirects the entire output of the loop to the file.
- for %i in (1,2,3) do @echo %i > myfile.txt
- Starts redirection anew each time the body of the loop is entered, losing the output of all but the latest loop iteration.
Links:
- Redirection at ss64.com
- Using command redirection operators at Microsoft
(…)
The command interpreter reloads the content of a batch after each execution of a line or a bracketed group.
If you start the following batch and change «echo A» to «echo B» in the batch shortly after starting it, the output will be B.
@echo off ping -n 6 127.0.0.1 >nul & REM wait echo A
What is on a single line does matter; changing «echo A» in the following batch after running it has no impact:
@echo off ping -n 6 127.0.0.1 >nul & echo A
Nor have after-start changes have any impact on commands bracketed with ( and ). Thus, changing «echo A» after starting the following batch has no impact:
@echo off for /L %%i in (1,1,10) do ( ping -n 2 127.0.0.1 >nul & REM wait echo A )
Ditto for any other enclosing, including this one:
@echo off ( ping -n 6 127.0.0.1 >nul & REM wait echo A )
The environment variables of the command interpreter process are inherited by the processes of any (external) commands that it executes. A few environment variables are used by the command interpreter itself. Changing them changes its operation.
Environment variables are affected by the SET, PATH, and PROMPT commands.
To unset a variable, set it to empty string, such as «set myvar=».
The command interpreter inherits its initial set of environment variables from the process that created it. In the case of command interpreters invoked from desktop shortcuts this will be Windows Explorer, for example.
Command interpreters generally have textual user interfaces, not graphical ones, and so do not recognize the Windows message that informs applications that the environment variable template in the Registry has been changed. Changing the environment variables in Control Panel will cause Windows Explorer to update its own environment variables from the template in the Registry, and thus change the environment variables that any subsequently invoked command interpreters will inherit. However, it will not cause command interpreters that are already running to update their environment variables from the template in the Registry.
See also #Variable substitution.
Links:
- Windows Environment Variables at ss64.com
- Command shell overview at TechNet / Microsoft Docs
The COMSPEC environment variable contains the full pathname of the command interpreter program file. This is just inherited from the parent process, and is thus indirectly derived from the setting of COMSPEC in the environment variable template in the Registry.
The value of the PATH environment variable comprises a list of directory names, separated by semi-colon characters. This is the list of directories that are searched, in order, when locating the program file of an external command to execute.
The value of the PATHEXT environment variable is a list of filename extensions separated by semicolons («;»). This is the list of filename extensions that are applied, in order, when locating the program file of an external command to execute.
An example content of PATHEXT printed by «echo %PATHEXT%»:
- .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
By adding «.PL» to the variable, you can ensure Perl programs get run from the command line even when typed without the «.pl» extension. Thus, instead of typing «mydiff.pl a.txt b.txt», you can type «mydiff a.txt b.txt».
Adding «.PL» to the variable in Windows Vista and later:
- setx PATHEXT %PATHEXT%;.PL
- If you use «set» available in Windows XP, the effect will be temporary and impacting only the current console or process.
Links:
- Windows Environment Variables at ss64
- Making Python scripts run on Windows without specifying “.py” extension at stackoverflow
The PROMPT environment variable controls the text emitted when the command interpreter displays the prompt. The command interpreter displays the prompt when prompting for a new command line in interactive mode, or when echoing a batch file line in batch file mode.
Various special character sequences in the value of the PROMPT environment variable cause various special effects when the prompt is displayed, as in the following table:
| Characters | Expansion Result |
|---|---|
| $$ | $ character itself |
| $A | & symbol AKA ampersand. A convenience, since it is difficult to place a literal & in the value of the PROMPT environment variable using the SET command. |
| $B | Vertical bar ‘|’ (pipe symbol) |
| $C | Left parenthesis ‘(‘ |
| $D | Current date |
| $E | ESC (ASCII code 27) |
| $F | Right parenthesis ‘)’ |
| $G | Greater-than symbol ‘>’ |
| $H | Backspace (deletes previous character) |
| $L | Less-than symbol ‘<‘ |
| $M | Remote name linked to the current drive if it is a network drive; empty string otherwise. |
| $N | Current drive letter |
| $P | Current drive letter and full path |
| $Q | ‘=’ (equals sign) |
| $S | ‘ ‘ (space character) |
| $T | Current system time |
| $V | Windows version number |
| $_ | <CR> (carriage return character, aka «enter») |
| $+ | As many plus signs (+) as there are items on the pushd directory stack |
Links:
- prompt at ss64
- prompt at Microsoft
Most Windows commands provide switches AKA options to direct their behavior.
Observations:
- Switches most often consist of a single-letter; some switches consist of a sequence of multiple letters.
- Switches are preceded with a slash (/) rather than, as in some other operating systems, with a minus sign (-).
- Switches are case-insensitive rather than, as in some other operating systems, case-sensitive.
- If a command from another operating system is ported to Windows (such as grep), it usually retains the option conventions from the original operating system, including the use of minus sign and case-sensitivity.
Examples:
- dir /?
- Outputs the help. This option is provided by many commands.
- dir /b /s
- Lists all files and folders in the current folder recursively. Two switches are used: b and s.
- dir /bs
- Does not work; switches cannot be accumulated behind a single slash.
- findstr /ric:»id: *[0-9]*» File.txt
- Unlike many other commands, findstr allows the accumulation of switches behind a single slash. Indeed, r, i and c are single-letter switches.
- dir/b/s
- Works. In dir, removing whitespace between the command and the first switch or between the switches does not make a difference; thus, does the same as dir /b /s.
- tree/f/a
- Does not work, unlike tree /f /a. In tree, separation by whitespace is mandatory. Nor does find/i/v work.
- dir /od
- The switch letter o is further modified by a single letter specifying that ordering should be by date. The letter d is not a switch by itself. Similar cases include dir /ad and more /t4.
- dir /B /S
- The switches are case-insensitive, unlike in some other operating systems.
- sort /r file.txt
- Sorts the file in a reverse order.
- sort /reverse file.txt
- Sort allows the switch string to be longer than a single-letter.
- sort /reve file.txt
- Sort allows the specified switch string to be a substring of the complete long name of the switch. Thus, does the same as the above.
- sort /reva file.txt
- Does not work, since «reva» is not a substring of «reverse».
- taskkill /im AcroRd32.exe
- Taskkill requires a multiletter switch name for /im; shortening to /i does not work.
- java -version
- Java, which originated in the environment of another operating system family, uses the minus convention for its switches AKA options.
- grep —help
- If GNU grep is installed, it requires multi-letter switches to be preceded by two dashes.
Commands usually set error level at the end of their execution. In Windows NT and later, it is a 32-bit signed integer; in MS DOS, it used to be an integer from 0 to 255. Keywords: return code, exit code, exit status.
The conventional meaning of the error level:
- 0 — success
- not 0 — failure
- The error levels being set are usually positive.
- If the command does not distinguish various kinds of failure, the error level on failure is usually 1.
Uses of the error level:
- It can be tested using && and ||; see also #Syntax.
- It can be tested using IF.
- The value can be accessed from ERRORLEVEL variable.
Examples:
- dir >NUL && echo Success
- The part after && is executed only if the error level is zero.
- color 00 || echo Failure
- The part after || is executed only if the error level is non-zero, whether positive or negative.
- color 00 || (
echo Failure
)- Multiline bracketing works as well.
- echo %ERRORLEVEL%
- Outputs the error level without changing it.
- if %errorlevel% equ 0 echo The error level is zero, meaning success.
- if %errorlevel% neq 0 echo The error level is non-zero, meaning failure.
- if errorlevel 1 echo The error level is >= 1, meaning failure via positive error level.
- Does not cover failure via negative error level. Note the «>=» part: this is not the same as if %errorlevel% equ 1.
- exit /b 1
- Returns a batch file, setting the error level to 1.
- cmd /c «exit /b 10»
- In the middle of a batch file or on the command line, sets the error level to 10.
- (cmd /c «exit /b 0» && Echo Success) & (cmd /c «exit /b -1» || Echo Failure)
- As above, showing the error level is indeed affected.
- (cmd /c «exit /b 0» & cmd /c «exit /b 1») || Echo Failure
- The error level of a chain created by & is the error level of the last command of the chain.
- cmd /c «exit /b -1» & if not errorlevel 1 echo Would-be success
- The «if not errorlevel 1» test, which might appear to test for success, passes on negative numbers: it tests on «not error level >= 1», which is «error level <= 0».
- set myerrorlevel=%errorlevel%
- Remembers the error level for later.
- set errorlevel=0
- To be avoided: overshadows the built-in errorlevel variable. Ensures that subsequent accesses via %ERRORLEVEL% return 0 rather than the actual error level.
- cmd /c «exit /b 0»
if 1 equ 1 ( cmd /c «exit /b 1» & echo %errorlevel% )- Outputs 0, since %errorlevel% gets expanded before cmd /c «exit /b 1» gets executed.
Links:
- Error level at ss64
Getting a substring of a non-empty variable:
set a=abcdefgh echo %a:~0,1% & rem from index 0, length 1; result: a echo %a:~1,1% & rem from index 1, length 1; result: b echo %a:~0,2% & rem from index 0, length 2; result: ab echo %a:~1,2% & rem from index 1, length 2; result: bc echo %a:~1% & rem from index 1 to the end; result: bcdefgh echo %a:~-1% & rem from index -1 (last char) to the end; result: h echo %a:~-2% & rem from index -2 (next-to-last) to the end; result: gh echo %a:~0,-2% & rem from index 0 to index -2, excl.; result: abcdef echo %a:~0,-1% & rem from index 0 to index -1, excl.; result: abcdefg echo %a:~1,-1% & rem from index 1 to index -1, excl.; result: bcdefg
Testing substring containment:
- if not «%a:bc=%»==»%a%» echo yes
- If variable a contains «bc» as a substring, echo «yes».
- This test is a trick that uses string replacement, discussed below.
- This test does not work if the variable contains a quotation mark.
Testing for «starts with»:
if %a:~0,1%==a echo yes & rem If variable a starts with "a", echo "yes". if %a:~0,2%==ab echo yes & rem If variable a starts with "ab", echo "yes".
String replacement:
set a=abcd & echo %a:c=% & rem replace c with nothing; result: abd set a=abcd & echo %a:c=e% & rem replace c with e; result: abed; set a=abcd & echo %a:*c=% & rem replace all up to c with nothing; result: d rem Above, the asterisk (*) only works at the beginning of the sought pattern.
See also the help for SET command: set /?.
Splitting a string by any of » «, «,» and «;»: [«space», «comma» and «semicolon»:]
set myvar=a b,c;d for %%a in (%myvar%) do echo %%a
Splitting a string by semicolon, assuming the string contains no quotation marks:
@echo off set myvar=a b;c;d set strippedvar=%myvar% :repeat for /f "delims=;" %%a in ("%strippedvar%") do echo %%a set prestrippedvar=%strippedvar% set strippedvar=%strippedvar:*;=% if not "%prestrippedvar:;=%"=="%prestrippedvar%" goto :repeat
Limitations:
- The above string processing does not work with parameter variables (%1, %2, …).
Links:
- Variables: extract part of a variable (substring) at ss64
- Variable Edit/Replace at ss64
The command-line arguments AKA command-line parameters passed to a batch script are accessible as %1, %2, …, %9. There can be more than nine arguments; to access them, see how to loop over all of them below.
The syntax %0 does not refer to a command-line argument but rather to the name of the batch file.
Testing for whether the first command-line argument has been provided:
if not -%1-==-- echo Argument one provided if -%1-==-- echo Argument one not provided & exit /b
A robust looping over all command-line arguments using SHIFT (for each command-line argument, …):
:argactionstart if -%1-==-- goto argactionend echo %1 & REM Or do any other thing with the argument shift goto argactionstart :argactionend
A robust looping over all command-line arguments using SHIFT without modifying %1, %2, etc.:
call :argactionstart %* echo Arg one: %1 & REM %1, %2, etc. are unmodified in this location exit /b :argactionstart if -%1-==-- goto argactionend echo %1 & REM Or do any other thing with the argument shift goto argactionstart :argactionend exit /b
Transferring command-line arguments to environment variables:
setlocal EnableDelayedExpansion REM Prevent affecting possible callers of the batch REM Without delayed expansion, !arg%argno%! used below won't work. set argcount=0 :argactionstart if -%1-==-- goto argactionend set /a argcount+=1 set arg%argcount%=%1 shift goto argactionstart :argactionend set argno=0 :loopstart set /a argno+=1 if %argno% gtr %argcount% goto loopend echo !arg%argno%! & REM Or do any other thing with the argument goto loopstart :loopend
Looping over all command-line arguments, albeit not a robust one:
for %%i in (%*) do ( echo %%i )
This looks elegant but is non-robust, maltreating arguments containing wildcards (*, ?). In particular, the above for command replaces arguments that contain wildcards (*, ?) with file names that match them, or drops them if no files match. Nonetheless, the above loop works as expected as long as the passed arguments do not contain wildcards.
Finding the number of command-line arguments, in a non-robust way:
set argcount=0 for %%i in (%*) do set /a argcount+=1
Again, this does not work with arguments containing wildcards.
The maximum possible number of arguments is greater than 4000, as empirically determined on a Windows Vista machine. The number can differ on Windows XP and Windows 7.
In passing arguments to a batch script, characters used for argument separation are the following ones:
- space
- comma
- semicolon
- equal sign
- horizontal tab character
Thus, the following lines pass the same four arguments:
- test.bat a b c d
- test.bat a,b,c,d
- test.bat a, b, c, d
- test.bat a;b;c;d
- test.bat a=b=c=d
- test.bat a b,c;,;=d
Yes, even the line with «a b,c;,;=d» passes four arguments, since a sequence of separating characters is considered a single separator.
To have a space, comma or semicolon in the argument value, you can pass the value enclosed in quotation marks. However, the quotation marks become part of the argument value. To get rid of the enclosing quotation marks when referring to the argument in the script, you can use %~<number> described in #Percent tilde.
When passing arguments to an invoked command rather than a batch script, you usually need to separate the command from the first argument using a space. However, for internal commands, that separation is not necessary if the first character after the command name is one of a couple of symbols, including .\/, and more:
- echo.
- Outputs a newline.
- tree.
- Fails: «tree.» not found. tree is an external command.
- dir..
- Lists the content of the parent directory.
- cd..
- Changes the current directory to the parent one.
- cd\
- Changes the current directory to the root one.
- start.
- Opens Windows Explorer from the current directory.
- dir/b/s
- Lists directory content recursively, showing full paths.
Links:
- Parameters / Arguments at ss64
- Escape Characters, Delimiters and Quotes at ss64
- Using batch parameters at Microsoft
Many commands accept file name wildcards—characters that do not stand for themselves and enable matching of a group of filenames.
Wildcards:
- * (asterisk): any sequence of characters
- ? (question mark): a single character other than a period («.») or, if part of a sequence of question marks at the end of a maximum period-free part of a file name, possibly zero number of characters; see examples for clarification
Examples:
- dir *.txt
- Matches Myfile.txt, Plan.txt and any other file with the .txt extension.
- dir *txt
- The period does not need to be included. However, this will also match files named without the period convention, such as myfiletxt.
- ren *.cxx *.cpp
- Renames all files with .cxx extension to have .cpp extension.
- dir a?b.txt
- Matches files aab.txt, abb.txt, a0b.txt, etc.
- Does not match ab.txt, since a question mark followed by a character other than a question mark or period cannot match zero characters.
- Does not match a.b.txt, since a question mark cannot match a period.
- dir ???.txt
- Matches .txt, a.txt, aa.txt, and aaa.txt, among others, since each question mark in the sequence followed by a period can match zero number of characters.
- dir a???.b???.txt???
- Matches a.b.txt, among others. While the last question mark sequence is not followed by a period, it is still a sequence at the end of a maximum period-free part of a file name.
- dir ????????.txt & @REM eight question marks
- Matches the same files as *.txt, since each file also has a short file name that has no more than 8 characters before .txt.
Quirk with short file names: the wildcard matching is performed both on long file names and the usually hidden short 8 chars + period + 3 chars file names. This can lead to bad surprises.
Unlike shells of some other operating systems, the cmd.exe shell does not perform wildcard expansion (replacement of the pattern containing wildcards with the list of file names matching the pattern) on its own. It is the responsibility of each program to treat wildcards as such. This enables such things as «ren *.txt *.bat», since the ren command actually sees the * wildcard rather than a list of files matching the wildcard. Thus, «echo *.txt» does not display files in the current folder matching the pattern but rather literally outputs «*.txt». Another consequence is that you can write «findstr a.*txt» without fearing that the «a.*txt» part gets replaced with the names of some files in the current folder. Furthermore, recursive «findstr /s pattern *.txt» is possible, while in some other operating systems, the «*.txt» part would get replaced with the file names found in the current folder, disregarding nested folders.
Commands accepting wildcards include ATTRIB, COPY, DIR, FINDSTR, FOR, REN, etc.
Links:
- Wildcards at ss64
- Using wildcard characters at Microsoft
You can get input from the user using the following methods:
- SET /P command
- CHOICE command
- Using «type con >myfile.txt», for which the multi-line user input is terminated by user pressing Control + Z.
When a command-line argument contains a file name, special syntax can be used to get various information about the file.
The following syntaxes expand to various information about the file passed as %1:
| Syntax | Expansion Result | Example |
|---|---|---|
| %~1 | %1 with no enclosing quotation marks | Not provided |
| %~f1 | Full path with a drive letter | C:\Windows\System32\notepad.exe |
| %~d1 | Drive letter | C: |
| %~p1 | Drive-less path with the trailing backslash | \Windows\System32\ |
| %~n1 | For a file, the file name without path and extension
For a folder, the folder name |
notepad |
| %~x1 | File name extension including the period | .exe |
| %~s1 | Modify of f, n and x to use short name | C:\PROGRA~2\WINDOW~3\ACCESS~1\wordpad.exe |
| %~a1 | File attributes | —a—— |
| %~t1 | Date and time of last modification of the file (format depends on Windows «Regional format» setting) | 02.11.2006 11:45 (example format as «English (United States)») |
| %~z1 | File size | 151040 |
| %~pn1 | A combination of p and n | \Windows\System32\notepad |
| %~dpnx1 | A combination of several letters | C:\Windows\System32\notepad.exe |
| %~$PATH:1 | The full path of the first match found in the folders present in the PATH variable, or an empty string in no match. | |
| %~n0 | %~n applied to %0:
The extensionless name of the batch |
tildetest |
| %~nx0 | %~nx applied to %0:
The name of the batch |
tildetest.bat |
| %~d0 | %~d applied to %0:
The drive letter of the batch |
C: |
| %~dp0 | %~dp applied to %0:
The folder of the batch with trailing backslash |
C:\Users\Joe Hoe\ |
The same syntax applies to single-letter variables created by FOR command, such as «%%i».
To learn about this subject from the command line, type «call /?» or «for /?».
Links:
- Parameters / Arguments at ss64
- Using batch parameters at Microsoft
- for at Microsoft
Functions AKA subprograms can be emulated using CALL, labels, SETLOCAL and ENDLOCAL.
An example of a function that determines arithmetic power:
@echo off call :power 2 4 echo %result% rem Prints 16, determined as 2 * 2 * 2 * 2 goto :eof rem __Function power______________________ rem Arguments: %1 and %2 :power setlocal set counter=%2 set interim_product=%1 :power_loop if %counter% gtr 1 ( set /a interim_product=interim_product * %1 set /a counter=counter - 1 goto :power_loop ) endlocal & set result=%interim_product% goto :eof
While the goto :eof at the end of the function is not really needed, it has to be there in the general case in which there is more than one function.
The variable into which the result should be stored can be specified on the calling line as follows:
@echo off call :sayhello result=world echo %result% exit /b :sayhello set %1=Hello %2 REM Set %1 to set the returning value exit /b
In the example above, exit /b is used instead of goto :eof to the same effect.
Also, remember that the equal sign is a way to separate parameters. Thus, the following items achieve the same:
- call :sayhello result=world
- call :sayhello result world
- call :sayhello result,world
- call :sayhello result;world
(See Command-line arguments as a reminder)
Links:
- Functions at ss64
Batch scripts can do simple 32-bit signed integer arithmetic and bitwise manipulation using SET /a command. The largest supported integer is 2147483647 = 2 ^ 31 — 1. The smallest supported integer is -2147483648 = — (2 ^ 31), assignable with the trick of set /a num=-2147483647-1. The syntax is reminiscent of the C language.
Arithmetic operators include *, /, % (modulo), +, -. In a batch, modulo has to be entered as «%%». There is no exponentiation operator.
Bitwise operators interpret the number as a sequence of 32 binary digits. These are ~ (complement), & (and), | (or), ^ (xor), << (left shift), >> (arithmetic AKA sign-preserving right shift). There is no logical AKA sign-erasing right shift and no bit rotation operators.
A logical operator of negation is !: it turns zero into one and non-zero into zero.
A combination operator is ,: it allows more calculations in one set command.
Combined assignment operators are modeled on «+=», which, in «a+=b», means «a=a+b». Thus, «a-=b» means «a=a-b». Similarly for *=, /=, %=, &=, ^=, |=, <<=, and >>=.
The precedence order of supported operators, is as follows:
- ( )
- * / % + —
- << >>
- &
- ^
- |
- = *= /= %= += -= &= ^= |= <<= >>=
- ,
Literals can be entered as decimal (1234), hexadecimal (0xffff, leading 0x), and octal (0777, leading 0).
The internal bit representation of negative integers is two’s complement. This provides for bit operations on negative integers, assignment and arithmetic results for hexadecimal literals larger than 0x7FFFFFFF and smaller or equal to 0xFFFFFFFF, and overflow and underflow behavior for arithmetic operations. For instance, -2147483648 is represented as 0x80000000, and therefore the binary complement operation «set /a num=~(-2147483647-1)» yields 2147483647, which equals 0x7FFFFFFF (type set /a num=0x7FFFFFFF to check). For another instance, «-2 & 0xF» yields 14 since -2 is 0xFFFFFFFE, which ANDed with 0xF yields 0xE, which is 14. While maximum decimal literal is 2147483647, maximum hexadecimal literal is 0xFFFFFFFF, which gets assigned as decadic -1. Similarly, 0xFFFFFFFE gets assigned as decadic -2, etc., and therefore, e.g. 0xFFFFFFFE — 2 yields -4. A hexadecimal literal larger than 0xFFFFFFFF is converted to -1, e.g. 0xFFFFFFFFFFFFFFFF, while a decimal literal larger than 2147483647 yields an error. The smallest representable 32-bit signed integer is -2147483648; «-2147483648» cannot be assigned directly since this is interpreted as -1 * 2147483648, and 2147483648 is larger than the maximum decimal literal 2147483647; however, -2147483647-1 does the trick, as does 0x80000000. «-2147483647-2» underflows to the largest positive integer, 2147483647; similarly, «-2147483647-3» underflows to 2147483646. In the other direction, «2147483647+1» overflows to -2147483648, which corresponds to the addition being performed on the internal bit representation as if unsigned; «2147483647+2» overflows to -2147483647, etc.
As some of the operators have special meaning for the command interpreter, an expression using them needs to be enclosed in quotation marks, such as this:
- set /a num=»255^127″
- set /a «num=255^127»
- Alternative placement of quotation marks.
- set /a num=255^^127
- Escape ^ using ^ instead of quotation marks.
Examples:
- set /a n=(2+3)*5
- Performs a simple calculation and stores the result in environment variable n. When called interactively (outside of a batch), outputs the result of calculation, otherwise outputs nothing.
- set /a (2+3)*5
- When called interactively (outside of a batch), outputs the result of calculation, otherwise outputs nothing. Changes no variable, being useful only for interactive use.
- set n1=40 & set n2=25
set /a n3=%n1%+%n2%
- Uses the standard percent notation for variable expansion.
- set n1=40 & set n2=25
set /a n3=n1+n2
- Avoids the percent notation around variable names as unneeded for /a.
- set /a num=»255^127″
- Encloses «^» in quotation marks to prevent its special meaning for the command interpreter.
- set /a n1 = (10 + 5)/5
- The spaces around = do not matter with /a. However, getting used to it lends itself to writing «set var = value» without /a, which sets the value of «var » rather than «var».
- if 1==1 (set /a n1=(2+4)*5)
- Does not work: the arithmetic brackets within grouping brackets cause trouble.
- if 1==1 (set /a n1=^(2+4^)*5)
- Escaping the arithmetic brackets with caret (^) works, as does enclosing «n1=2+(4*5)» in quotation marks.
- set /a n1=2+3,n2=4*7
- Performs two calculations.
- set /a n1=n2=2
- Has the same effect as n1=2,n2=2.
- set n1=40 & set n2=25 & set /a n3=n1+n2
- Works as expected.
- set /a n1=2,n2=3,n3=n1+n2
- Works as expected.
- set n1=40 & set n2=25 & set /a n3=%n1%+%n2%
- Does not work unless n1 and n2 were set previously. The variable specifications «%n1%» and «%n2″% get expanded before the first set command is executed. Dropping percent notation makes it work.
- set /a n1=2,n2=3,n3=%n1%+%n2%
- Does not work unless n1 and n2 were set previously, for the reason stated in the previous example.
- set /a n1=0xffff
- Sets n1 using hexadecimal notation, to «65535».
- set /a n1=0777
- Sets n1 using octal notation, to «511».
- set /a n1=0xffffffff
- Sets n1 to -1.
- set /a n1=»~0″
- Sets n1 to -1, in keeping with the underlying two’s complement representation of negative integers. Thus, bitwise complements (~) of non-negative integers yield negative integers.
- set /a «n1=-1>>1»
- Outputs -1 as a result of the «>>» operator being an arithmetic right shift, preserving the highest bit of the underlying bitwise representation of the signed 32-bit integer. Note that -1 is internally 0xFFFFFFFF. Logical right shift (highest-bit-dropping one) would result in 0x7FFFFFFF, the maximum positive 32-bit integer.
- set /a «n1=(-1>>1) & 0x7FFFFFFF»
- Emulates logical right shift (highest-bit-dropping one) by 1 by clearing the highest bit of the underlying bitwise representation of the 32-bit signed integer.
- set /a «n=-1, shiftcount=4, n1=(n>>shiftcount) & (0x7FFFFFFF >> (shiftcount-1))»
- Emulates logical right shift for shiftcount > 0, which when by more than 1 bit requires clearing multiple highest bits.
- set /a «n1=1<<32»
- Yields 0 for the right operand being 32 or higher, or when negative. This is unlike the behavior of the left shift instruction on modern x86 processors, which for 32-bit registers masks the right operand to constrain it to 5 bits. Thus, using the x86 instruction, the result would be 1 since 32 & 0x1F is 0. In the C language, the result is undefined and the actual result is platform dependent.
- set /a n1=%random%
- A pseudo-random number from 0 to 32767 = 2^15-1.
- set /a n1=»%random%>>10″
- A pseudo-random number from 0 to 31 = 2^5-1. The shift right operator drops 10 out of 15 bits, keeping 5 bits.
- set /a n1=%random%%50
- A pseudo-random number from 0 to 49. Uses the % modulo operator. In a batch, %% is needed for modulo: set /a n1=%random%%%50. Because of this particular use of the modulo, the result is not perfectly uniform; it is uniform if the 2nd modulo operand—above 50—equals to a power of 2, e.g. 256 = 2^8.
- set /a n1=»(%random%<<15)+%random%»
- A pseudo-random number from 0 to 1073741823 = 2^30 — 1. Combines the two 15-bit random numbers produced by %random% alone to produce a single 30-bit random number..
- set /a n1=»((%random%<<15)+%random%)%1000000″
- As above, but again using modulo, this time to achieve the range 0 to 999999.
An example calculation that prints prime numbers:
@echo off setlocal set n=1 :print_primes_loop set /a n=n+1 set cand_divisor=1 :print_primes_loop2 set /a cand_divisor=cand_divisor+1 set /a cand_divisor_squared=cand_divisor*cand_divisor if %cand_divisor_squared% gtr %n% echo Prime %n% & goto :print_primes_loop set /a modulo=n%%cand_divisor if %modulo% equ 0 goto :print_primes_loop & REM Not a prime goto :print_primes_loop2
Links:
- set at ss64.com
- set at Microsoft
- Random Numbers at ss64.com
- Rules for how CMD.EXE parses numbers by dbenham, dostips.com
- Bitwise operations # Batch File, rosettacode.org
Files can be found using #DIR, #FOR, #FINDSTR, #FORFILES, and #WHERE.
Examples:
- dir /b /s *base*.doc*
- Outputs all files in the current folder and its subfolders such that the file name before the extension contains the word «base» and whose extension starts with «doc», which includes «doc» and «docx». The files are output with full paths, one file per line.
- dir /b /s *.txt | findstr /i pers.*doc
- Combines the result of outputting files including their complete paths with the findstr filtering command supporting limited regular expressions, yielding a versatile and powerful combination for finding files by names and the names of their directories.
- for /r %i in (*) do @if %~zi geq 1000000 echo %~zi %i
- For each file in the current folder and its subfolders that has the size greater than or equal to 1,000,000 bytes, outputs the file size in bytes and the full path of the file. For the syntax in %~zi, see #Percent tilde.
- forfiles /s /d 06/10/2015 /c «cmd /c echo @fdate @path»
- For each file in the current folder and its subfolders modified on 10 June 2015 or later, outputs the file modification date and full file path. The date format after /d is locale specific. Thus, allows to find most recently modified files.
- (for /r %i in (*) do @echo %~ti :: %i) | findstr 2015.*::
- Searching the current folder recursively, outputs files whose last modification date is in year 2015. Places the modification date and time, followed by a double colon, before the file name. Works as long as the used version of Windows and locale displays dates in a format that contains four-digit years. The double colon is used to make sure the findstr command is matching the date and not the file name.
- for /r %i in (*) do @echo %~ti | findstr 2015 >NUL && echo %i
- As above, outputs files changed in 2015. Unlike the above, only outputs the files, not the modification dates.
- findstr /i /s /m cat.*mat *.txt
- Finds files by their content. Performs a full text search for regular expression cat.*mat in files with names ending in .txt, and outputs the files names. The /m switch ensures only the file names are output.
- where *.bat
- Outputs all .bat files in the current directory and in the directories that are in PATH.
When using Windows command line from the standard console that appears after typing cmd.exe after pressing Windows + R, you can use multiple keyboard shortcuts, including function keys:
- Tab: Completes the relevant part of the typed string from file names or folder names in the current folder. The relevant part is usually the last space-free part, but use of quotation marks changes that. Generally considers both files and folders for completion, but cd command only considers folders.
- Up and down arrow keys: Enters commands from the command history, one at a time.
- Escape: Erases the current command line being typed.
- F1: Types the characters from the single previously entered command from the command history, one character at a time. Each subsequent press of F1 enters one more character.
- F2: Asks you to type a character, and enters the shortest prefix of the previous command from the command history that does not include the typed character. Thus, if the previous command was echo Hello world and you typed o, enters ech.
- F3: Enters the single previous command from the command history. Repeated pressing has no further effect.
- F4: Asks you to type a character, and erases the part of the currently typed string that starts at the current cursor location, continues to the right, and ends with the character you entered excluding that character. Thus, if you type echo Hello world, place the cursor at H using left arrow key, press F4 and then w, you get echo world. If you press F4 and then Enter, erases the text from the cursor to the end of the line.
- F5: Enters previous commands from the command history, one at a time.
- F6: Enters Control+Z character.
- F7: Opens a character-based popup window with the command history, and lets you use arrow key and enter to select a command. After you press enter in the popup, the command is immediately executed.
- F8: Given an already typed string, shows items from the command history that have that string as a prefix, one at a time.
- F9: Lets you enter the number of the command from the command history, and then executes the command.
- Alt + F7: Erases the command history.
The above are also known as command prompt keyboard shortcuts.
The availability of the above shortcuts does not seem to depend on running DOSKEY.
Links:
- Windows Keyboard shortcuts at ss64.com
- doskey at Microsoft
File and directory paths follow certain conventions. These include the possible use of a drive letter followed by a colon (:), the use of backslash (\) as the path separator, and the distinction between relative and absolute paths.
Forward slash (/) often works when used instead of (\) but not always; it is normally used to mark switches (options). Using forward slash can lead to various obscure behaviors, and is best avoided.
Special device names include NUL, CON, PRN, AUX, COM1, …, COM9, LPT1, …, LPT9; these can be redirected to.
Examples:
- attrib C:\Windows\System32\notepad.exe
- Succeeds if the file exists, as it should. This is an absolute path with a drive letter. It is also known as a fully qualified path.
- attrib \Windows\System32\notepad.exe
- Succeeds if the current drive is C:, and if the file exists, as it should. This is an absolute path without a drive letter.
- cd /d C:\Windows & attrib System32\notepad.exe
- Succeeds if the file exists. The path given to attrib is a relative path.
- cd /d C:\Windows\System32 & attrib C:notepad.exe
- Succeeds if the file exists. The path given to attrib is a relative one despite containing a drive letter: there would have to be C:\notepad.exe with a backslash for that to be an absolute path.
- cd /d C:\Windows & attrib .\System32\notepad.exe
- Succeeds if the file exists. A single period denotes the current folder.
- attrib .
- A single period denotes the current folder.
- cd /d C:\Windows & attrib .\System32\\\notepad.exe
- Succeeds if the file exists. Piling of backslashes has no impact beyond the first backslash.
- cd /d C:\Windows & attrib .\System32
- Succeeds if the folder exists.
- cd /d C:\Windows & attrib .\System32\
- Fails. Folders are usually denoted without the final backslash.
- cd C:\Windows\System32\
- Succeeds, whyever.
- cd ..
- A double period denotes the parent folder.
- attrib C:\Windows\System32\..\..\Windows\System32
- A double period can be used in the middle of the path to navigate to the parent folder, even multiple times.
- attrib \\myserver\myvolume
- A network UNC path starts with double backslash and no drive letter.
- cd \\myserver\myvolume
- Does not work; changing to a server folder in this direct manner does not work.
- pushd \\myserver\folder
- Automatically creates a drive for the folder and changes to it. After you use #POPD, the drive gets unassigned again.
- attrib C:/Windows/System32/notepad.exe
- Succeeds on multiple versions of cmd.exe. Uses forward slashes.
Links:
- Long filenames, NTFS and legal filename characters at ss64.com
- Naming Files, Paths, and Namespaces at Microsoft
- W:Path (computing)#MS-DOS/Microsoft Windows style, wikipedia.org
- Why does the cmd.exe shell on Windows fail with paths using a forward-slash (‘/) path separator?, stackoverflow.com
Arrays can be emulated in the delayed expansion mode using the combination of % and ! to indicate variables. There, %i% is the value of variable i with the immediate expansion while !i! is the value of variable i in the delayed expansion.
@echo off setlocal EnableDelayedExpansion for /l %%i in (1, 1, 10) do ( set array_%%i=!random! ) for /l %%i in (1, 1, 10) do ( echo !array_%%i! ) :: For each item in the array, not knowing the length set i=1 :startloop if not defined array_%i% goto endloop set array_%i%=!array_%i%!_dummy_suffix echo A%i%: !array_%i%! set /a i+=1 goto startloop :endloop
Links:
- Arrays, linked lists and other data structures in cmd.exe (batch) script, stackoverflow.com
Some tasks can be conveniently achieved with Perl one-liners. Perl is a scripting language originating in the environment of another operating system. Since many Windows computing environments have Perl installed, Perl one-liners are a natural and compact extension of Windows batch scripting.
Examples:
- echo «abcbbc»| perl -pe «s/a.*?c/ac/»
- Lets Perl act as sed, the utility that supports textual replacements specified using regular expressions.
- echo a b| perl -lane «print $F[1]»
- Lets Perl act as cut command, displaying the 2nd field or column of the line, in this case b. Use $F[2] to display 3rd field; indexing starts at zero. Native solution: FOR /f.
- perl -ne «print if /\x22hello\x22/» file.txt
- Acts as grep or FINDSTR, outputting the lines in file.txt that match the regular expression after if. Uses the powerful Perl regular expressions, more powerful than those of FINDSTR.
- perl -ne «$. <= 10 and print» MyFile.txt
- Lets Perl act as head -10 command, outputting the first 10 lines of the file.
- perl -e «sleep 5»
- Waits for 5 seconds.
- for /f %i in (‘perl -MPOSIX -le «print strftime ‘%Y-%m-%d’, localtime»‘) do @set isodate=%i
- Gets current date in the ISO format into isodate variable.
- perl -MWin32::Clipboard -e «print Win32::Clipboard->Get()»
- Outputs the text content of the clipboard. When stored to getclip.bat, yields a handy getclip command to complement CLIP command.
- perl -MText::Diff -e «print diff ‘File1.txt’, ‘File2.txt'»
- Outputs differences between two files in a format similar to diff command known from other operating systems, including context lines, lines starting with + and lines starting with -.
- perl -MWin32::Sound -e «Win32::Sound::Play(‘C:\WINDOWS\Media\notify.wav’);»
- Plays notification sound in notify.wav without showing any window.
On the web, Perl one-liners are often posted in the command-line conventions of another operating system, including the use of apostrophe (‘) to surround the arguments instead of Windows quotation marks. These need to be tweaked for Windows.
Links:
- Perl One Liners at novosial.org
- Why doesn’t my Perl one-liner work on Windows? at stackoverflow.com
- W:One-liner program#Perl
Windows cmd.exe command interpreter can use commands from Unix-like operating systems, provided they are installed. Example commands include grep, sed, awk, wc, head and tail. The commands are available from GNU project, and their Windows ports exist. You can learn more about the commands in Guide to Unix Wikibook. Beware that batch programs that come to depend on these commands are not guaranteed to work on other Windows machines.
Freely licensed Windows versions of GNU commands can be obtained from the following projects:
- GnuWin32, sourceforge.net
- ezwinports, sourceforge.net: has some fresher ports than GnuWin32
An alternative way of running GNU commands for Windows 10 is Windows Subsystem for Linux.
There is no touch command familiar from other operating systems. The touch command would modify the last-modification timestamp of a file without changing its content.
One workaround, with unclear reliability and applicability across various Windows versions, is this:
- copy /b file.txt+,,
Links:
- Windows recursive touch command at superuser.com
- Windows version of the Unix touch command at stackoverflow.com
There is no built-in command to get last lines of a file; no equivalent of tail command. However, a batch can be written to do the job and is available from the link below. Alternatively, one can install tail command for Windows, or run a PowerShell equivalent with no installation required.
Links:
- CMD.EXE batch script to display last 10 lines from a txt file, stackoverflow.com
There is no preinstalled hex dump tool to view file content in hexadecimal. Nonetheless, there are the following options:
1) Use fsutil file createnew to create a file of all zero bytes and use fc to view the bytes via comparison:
- fsutil file createnew allzeros.bin 1000
fc /b C:\Windows\notepad.exe allzeros.bin- The notepad.exe bytes that are zero are not shown in the comparison, but other bytes are shown with their offset, one byte per line. You can determine how many initial bytes you want to see by choosing the length of the all-zero-byte file by changing the final 1000 above. To view complete file, create the all-zero-byte file of the length of the inspected file. Far from perfect, but can be used as a quick hack to view e.g. BOM marks or the kind of newlines used.
2) Use certutil -encodeHex, where the encodeHex feature is not officially documented:
- certutil -encodeHex file.txt filehex.txt
- Writes the file content of file.txt in hexadecimal to filehex.txt. Refuses to overwrite filehex.txt if it exists. You cannot limit the number of bytes to be converted.
3) Use PowerShell 5.0 Format-Hex:
- powershell Format-Hex C:\Windows\notepad.exe
- Option -Count is supported in latest PowerShell.
4) Install a command such as the feature-rich od or hexdump; see Unix commands. od can do octal dump as well.
5) If you are on old 32-bit version of Windows (not very likely), use debug; see DEBUG.
Links:
- fc, docs.microsoft.com
- certutil, ss64.com
- certutil, docs.microsoft.com
- Format-Hex, docs.microsoft.com
- HEXDUMP.BAT version 2.1 using CERTUTIL by Dave Benham, dostips.com
- New function — :hexDump by Dave Benham, dostips.com — pure batch; heavy batch magic and also slow
If your user has elevated administration privileges, you can use these if you start cmd.exe in a particular way. To start cmd.exe with these elevated privileges, you can do the following.
- Select Start menu and type «cmd.exe» there.
- Right-click on the cmd.exe icon and select Run as administrator.
To test whether you have elevated privileges:
- Run «net session», which will fail if you do not have the privileges.
Limitations include the following:
- No while loop; can be emulated via labels and goto. There is a for loop and an if statement.
- No break and continue statements for loop control known from the C language.
- No proper custom functions; a custom function can be created using labels, call and %n parameter expansion.
- Fragile processing of strings with special characters such as quotation marks («) or ampersands (&).
- No arrays; can be emulated in a limited manner.
- No associative arrays AKA dictionaries.
- No floating-point arithmetic.
- No ternary conditional operator from the C language.
- No function to convert a character to its ascii value or to convert an ascii value to a character. No sane workarounds.
- No arbitrarily large integer arithmetic.
- No touch command to change file timestamp from other operating systems; no head and tail commands.
- No GUI programming.
- And more.
These commands are all built in to the command interpreter itself, and cannot be changed. Sometimes this is because they require access to internal command interpreter data structures, or modify properties of the command interpreter process itself.
| Command | Description |
|---|---|
| ASSOC | Associates an extension with a file type (FTYPE). |
| BREAK | Sets or clears extended CTRL+C checking. |
| CALL | Calls one batch program from another. |
| CD, CHDIR | Outputs or sets the current directory. |
| CHCP | Outputs or sets the active code page number. |
| CLS | Clears the screen. |
| COLOR | Sets the console foreground and background colors. |
| COPY | Copies files. |
| DATE | Outputs and sets the system date. |
| DEL, ERASE | Deletes one or more files. |
| DIR | Outputs a list of files and subdirectories in a directory. |
| ECHO | Outputs messages, or turns command echoing on or off. |
| ELSE | Performs conditional processing in batch programs when «IF» is not true. |
| ENDLOCAL | Ends localization of environment changes in a batch file. |
| EXIT | Quits the CMD.EXE program (command interpreter). |
| FOR | Runs a specified command for each file in a set of files. |
| FTYPE | Sets the file type command. |
| GOTO | Goes to a label. |
| IF | Performs conditional processing in batch programs. |
| MD, MKDIR | Creates a directory. |
| MOVE | Moves a file to a new location |
| PATH | Sets or modifies the PATH environment |
| PAUSE | Causes the command session to pause for user input. |
| POPD | Changes to the drive and directory popped from the directory stack |
| PROMPT | Sets or modifies the string displayed when waiting for input. |
| PUSHD | Pushes the current directory onto the stack, and changes to the new directory. |
| RD / RMDIR | Removes the directory. |
| REM | A comment command. Unlike double-colon (::), the command can be executed. |
| REN / RENAME | Renames a file or directory. |
| SET | Sets or outputs shell environment variables. |
| SETLOCAL | Creates a child-environment for the batch file. |
| SHIFT | Moves the batch parameters forward. |
| START | Starts a program with various options. |
| TIME | Outputs or sets the system clock. |
| TITLE | Changes the window title |
| TYPE | Prints the content of a file to the console. |
| VER | Shows the command processor, operating system versions. |
| VERIFY | Verifies that file copy has been done correctly. |
| VOL | Shows the label of the current volume. |
Associates an extension with a file type (FTYPE), outputs existing associations, or deletes an association. See also FTYPE.
Examples:
- assoc
- Lists all associations, in the format «<file extension>=<file type>», as, for example, «.pl=Perl» or «.xls=Excel.Sheet.8».
- assoc | find «.doc»
- Lists all associations containing «.doc» substring.
Links:
- assoc at ss64.com
- assoc at Microsoft
- Making Python scripts run on Windows without specifying “.py” extension at stackoverflow
In Windows versions based on Windows NT, does nothing; kept for compatibility with MS DOS.
Examples:
- break > empty.txt
- Creates an empty file or to clears the content of an existing file, taking advantage of the fact that break does nothing and has no output. Shorter to type than «type nul > empty.txt».
Links:
- break at Microsoft
Calls one batch program from another, calls a subprogram within a single batch program, or, as an undocumented behavior, starts a program. In particular, suspends the execution of the caller, starts executing the callee, and resumes the execution of the caller if and when the callee finishes execution.
For calling a subprogram, see Functions section.
Beware that calling a batch program from a batch without using the call keyword results in the execution never returning to the caller once the callee finishes.
The callee inherits environment variables of the caller, and unless the callee prevents that via SETLOCAL, changes made by the callee to environment variables become visible to the caller once it resumes execution.
Examples:
- mybatch.bat
- If used in a batch, transfers control to mybatch.bat and never resumes the execution of the caller.
- call mybatch.bat
- call mybatch
- call mybatch.bat arg1 «arg 2»
- call :mylabel
- call :mylabel arg1 «arg 2»
- cmd /c mybatch.bat
- Similar to call, but resumes execution even when there are errors. Furthermore, any changes the callee makes to environment variables are not propagated to the caller.
- call notepad.exe
- Launches Notepad, or in general, any other executable. This is apparently not the intended usage of call, and is not officially documented.
See also Functions, CMD amd START.
Links:
- call at ss64.com
- call at Microsoft
- CALL command vs. START with /WAIT option, stackoverflow.com
Changes to a different directory, or outputs the current directory. However, if a different drive letter is used, it does not switch to that different drive or volume.
Examples:
- cd
- Outputs the current directory, e.g. C:\Windows\System32.
- cd C:\Program Files
- No surrounding quotes are needed around paths with spaces.
- cd \Program Files
- cd Documents
- cd %USERPROFILE%
- cd /d C:\Program Files
- Changes to the directory of the C: drive even if C: is not the current drive.
- C: & cd C:\Program Files.
- Changes to the directory of the C: drive even if C: is not the current drive.
- cd ..
- Changes to the parent directory. Does nothing if already in the root directory.
- cd ..\..
- Changes to the parent directory two levels up.
- C: & cd C:\Windows\System32 & cd ..\..\Program Files
- Uses «..» to navigate through the directory tree up and down
- cd \\myserver\folder
- Does not work. Changing the directory directly to a network Universal Naming Convention (UNC) folder does not work. Keywords: UNC path.
- subst A: \\myserver\folder && cd /d A:
- Changes the directory to a server folder with the use of #SUBST command, assuming drive letter A: is free.
- pushd \\myserver\folder
- Automatically creates a drive for the folder and changes to it. After you use #POPD, the drive gets unassigned again.
- cd C:\W*
- Changes to C:\Windows, in a typical Windows setup. Thus, wildcards work. Useful for manual typing from the command line.
- cd C:\W*\*32
- Changes to C:\Windows\System32, in a typical Windows setup.
Links:
- cd at ss64.com
- cd at Microsoft
A synonym of CD.
Clears the screen.
Sets the console foreground and background colors.
Examples:
- color f9
- Use white background and blue foreground.
- color
- Restore the original color setting.
Links:
- color at ss64.com
- color at Microsoft
Copies files. See also MOVE, XCOPY and ROBOCOPY.
Examples:
- copy F:\File.txt
- Copies the file into the current directory, assuming the current directory is not F:\.
- copy «F:\My File.txt»
- As above; quotation marks are needed to surround a file with spaces.
- copy F:\*.txt
- Copies the files located at F:\ and ending in dot txt into the current directory, assuming the current directory is not F:\.
- copy F:\*.txt .
- Does the same as the above command.
- copy File.txt
- Issues an error message, as File.txt cannot be copied over itself.
- copy File1.txt File2.txt
- Copies File1.txt to File2.txt, overwriting File2.txt if confirmed by the user or if run from a batch script.
- copy File.txt «My Directory»
- Copies File.txt into «My Directory» directory, assuming «My Directory» exists.
- copy Dir1 Dir2
- Copies all files directly located in directory Dir1 into Dir2, assuming Dir1 and Dir2 are directories. Does not copy files located in nested directories of Dir1.
- copy *.txt *.bak
- For each *.txt file in the current folder, makes a copy ending with «bak» rather than «txt».
Links:
- copy at ss64.com
- copy at Microsoft
Deletes files. Use with caution, especially in combination with wildcards. Only deletes files, not directories, for which see RD. For more, type «del /?».
Examples:
- del File.txt
- del /s *.txt
- Deletes the files recursively including nested directories, but keeps the directories; mercilessly deletes all matching files without asking for confirmation.
- del /p /s *.txt
- As above, but asks for confirmation before every single file.
- del /q *.txt
- Deletes without asking for confirmation.
Links:
- del at ss64.com
- del at Microsoft
Lists the contents of a directory. Offers a range of options. Type «dir /?» for more help.
Examples:
- dir
- Lists the files and folders in the current folder, excluding hidden files and system files; uses a different manner of listing if DIRCMD variable is non-empty and contains switches for dir.
- dir D:
- dir /b C:\Users
- dir /s
- Lists the contents of the directory and all subdirectories recursively.
- dir /s /b
- Lists the contents of the directory and all subdirectories recursively, one file per line, displaying complete path for each listed file or directory.
- dir *.txt
- Lists all files with .txt extension.
- dir /a
- Includes hidden files and system files in the listing.
- dir /ah
- Lists hidden files only.
- dir /ad
- Lists directories only. Other letters after /A include S, I, R, A and L.
- dir /ahd
- Lists hidden directories only.
- dir /a-d
- Lists files only, omitting directories.
- dir /a-d-h
- Lists non-hidden files only, omitting directories.
- dir /od
- Orders the files and folders by the date of last modification. Other letters after /O include N (by name), E (by extension), S (by size), and G (folders first)
- dir /o-s
- Orders the files by the size descending; the impact on folder order is unclear.
- dir /-c /o-s /a-d
- Lists files ordered by size descending, omitting the thousands separator via /-C, excluding folders.
- dir /s /b /od
- Lists the contents of the directory and all subdirectories recursively, ordering the files in each directory by the date of last modification. The ordering only happens per directory; the complete set of files so found is not ordered as a whole.
- dir /a /s
- Lists files recursively including hidden files and system files. Can be used to find out the disk usage (directory size), by considering the final lines of the output.
Links:
- dir at ss64.com
- dir at Microsoft
Outputs or sets the date. The way the date is output depends on country settings. Date can also be output using «echo %DATE%».
Getting date in the iso format, like «2000-01-28»: That is nowhere easy, as the date format depends on country settings.
- If you can assume the format of «Mon 01/28/2000», the following will do:
- set isodate=%date:~10,4%-%date:~4,2%-%date:~7,2%
- If you have WMIC, the following is locale independent:
- for /f %i in (‘wmic os get LocalDateTime’) do @if %i lss a if %i gtr 0 set localdt=%i
set isodate=%localdt:~0,4%-%localdt:~4,2%-%localdt:~6,2% - To use the above in a batch, turn %i into %%i and remove @ from before if.
- for /f %i in (‘wmic os get LocalDateTime’) do @if %i lss a if %i gtr 0 set localdt=%i
- If you have Perl installed:
- for /f %i in (‘perl -MPOSIX -le «print strftime ‘%Y-%m-%d’, localtime»‘) do @set isodate=%i
Links:
- date at ss64.com
- date at Microsoft
- How to get current datetime on Windows command line, in a suitable format for using in a filename? at stackoverflow
Outputs messages, or turns command echoing on or off.
Examples:
- echo on
- @echo off
- echo Hello
- echo «hello»
- Outputs the quotes too.
- echo %PATH%
- Outputs the contents of PATH variable.
- echo Owner ^& son
- Uses caret (^) to escape ampersand (&), thereby enabling echoing ampersands.
- echo 1&echo 2&echo 3
- Outputs three strings, each followed by a newline.
- echo.
- Outputs a newline while the period is not being output. Without the period, outputs «echo off» or «echo on». Adding a space before the period leads to the period being output. Other characters having the same effect as period include :;,/\(=+[].
- echo %random%>>MyRandomNumbers.txt
- While it seems to output random numbers to MyRandomNumbers.txt, it actually does not do so for numbers 0-9, since these, when placed before >>, indicate which channel is to be redirected. See also #Redirection.
- echo 2>>MyRandomNumbers.txt
- Instead of echoing 2, redirects standard error to the file.
- (echo 2)>>MyRandomNumbers.txt
- Echoes even a small number (in this case 2) and redirects the result.
- >>MyRandomNumbers.txt echo 2
- Another way to echo even a small number and redirect the result.
Displaying a string without a newline requires a trick:
- set <NUL /p=Output of a command:
- Outputs «Output of a command:». The output of the next command will be displayed immediately after «:».
- set <NUL /p=Current time: & time /t
- Outputs «Current time: » followed by the output of «time /t».
- (set <NUL /p=Current time: & time /t) >tmp.txt
- Like before, with redirecting the output of both commands to a file.
Links:
- echo at ss64.com
- echo at Microsoft
An example:
if exist file.txt ( echo The file exists. ) else ( echo The file does not exist. )
See also IF.
Ends local set of environment variables started using SETLOCAL. Can be used to create subprograms: see Functions.
Links:
- endlocal at ss64.com
- endlocal at Microsoft
A synonym of DEL.
Exits the DOS console or, with /b, only the currently running batch or the currently executed subroutine. If used without /b in a batch file, causes the DOS console calling the batch to close.
Examples:
- exit
- exit /b
Links:
- exit at ss64.com
- exit at Microsoft
Iterates over a series of values, executing a command. Keywords: loop.
In the following examples, %i is to be used from the command line while %%i is to be used from a batch.
The index (e.g., %i) must be a single character variable name.
Examples without switches and with /r and /d switches:
- for %%i in (1,2,3) do echo %%i
- In a batch, echoes 1, 2, and 3. In a batch, the command must use a double percent sign.
- The remaining examples are intended to be directly pasted into a command line, so they use a single percent sign and include «@» to prevent repetitive display.
- for %i in (1,2,3) do @echo %i
- From a command line, echoes 1, 2, and 3.
- The for command tries to interpret the items as file names and as patterns of file names containing wildcards.
- It does not complain if the items do not match existing file names, though.
- for %i in (1,2,a*d*c*e*t) do @echo %i
- Unless you happen to have a file matching the third pattern, echoes 1 and 2, discarding the third item.
- for %i in (1 2,3;4) do @echo %i
- Echoes 1, 2, 3, and 4. Yes, a mixture of item separators is used.
- for %i in (*.txt) do @echo %i
- Echoes file names of files located in the current folder and having the .txt extension.
- for %i in («C:\Windows\system32\*.exe») do @echo %i
- Echoes file names matching the pattern.
- for /r %i in (*.txt) do @echo %i
- Echoes file names with full paths, of files having the extension .txt located anywhere in the current folder including nested folders.
- for /d %i in (*) do @echo %i
- Echoes the names of all folders in the current folder.
- for /r /d %i in (*) do @echo %i
- Echoes the names including full paths of all folders in the current folder, including nested folders.
- for /r %i in (*) do @if %~zi geq 1000000 echo %~zi %i
- For each file in the current folder and its subfolders that has the size greater than or equal to 1,000,000 bytes, outputs the file size in bytes and the full path of the file. For the syntax in %~zi, see #Percent tilde.
Examples of /l switch:
- for /l %i in (1,2,11) do @echo %i
- Echoes the numbers from 1 to 11 with step 2. Thus, the format is (start, step, end). 32-bit signed integers are supported.
- for /l %i in (10,-1,1) do @echo %i
- Echoes the numbers from 10 to 1 descending.
- for /l %i in (1,0,1) do @echo %i
- Keeps echoing 1; an infinite loop.
- for /l %i in (0) do @echo %i
- Keeps echoing 0; an infinite loop.
- for /l %i in () do @echo %i
- Keeps echoing 0; an infinite loop.
- for /l %i in (-10,1) do @echo %i
- Echoes the numbers from -10 to 0; the unstated end limit integer is taken to be zero.
- for /l %i in (0xF, 1, 020) do @echo %i
- Echoes the numbers from 15 to 16; thus, hexadecimal and octal literals are supported.
- for /l %i in (2147483646,1,2147483647) do @echo %i
- Echoes 2147483646, then 2147483647, then -2147483648, then -2147483647, and so on. This is probably caused by an increment of 2147483647 overflowing to -2147483648.
- for /l %i in (-2147483648,1,-2147483647) do @echo %i
- Echoes -2147483648 and then -2147483647. Thus, directly supports -2147483648 literal, unlike set /a.
Examples with /f switch:
- for /f «tokens=*» %i in (list.txt) do @echo %i
- For each line in a file, echoes the line.
- for /f «tokens=*» %i in (list1.txt list2.txt) do @echo %i
- For each line in the files, echoes the line.
- for /f «tokens=*» %i in (*.txt) do @echo %i
- Does nothing. Does not accept wildcards to match file names.
- for /f «tokens=1-3 delims=:» %a in («First:Second::Third») do @echo %c-%b-%a
- Parses a string into tokens delimited by «:».
- The quotation marks indicate the string is not a file name.
- The second and third tokens are stored in %b and %c even though %b and %c are not expressly mentioned in the part of the command before «do».
- The two consecutive colons are treated as one separator; %c is not «» but rather «Third».
- Does some of the job of the cut command from other operating systems.
- for /f «tokens=1-3* delims=:» %a in («First:Second::Third:Fourth:Fifth») do @echo %c-%b-%a: %d
- As above, just that the 4th and 5th items get captured in %d as «Fourth:Fifth», including the separator.
- for /f «tokens=1-3* delims=:,» %a in («First,Second,:Third:Fourth:Fifth») do @echo %c-%b-%a: %d
- Multiple delimiters are possible.
- for /f «tokens=1-3» %a in («First Second Third,item») do @echo %c-%b-%a
- The default delimiters are space and tab. Thus, they differ from the separators used to separate arguments passed to a batch.
- for /f «tokens=*» %i in (‘cd’) do @echo %i
- For each line of the result of a command, echoes the line.
- for /f «tokens=*» %i in (‘dir /b /a-d-h’) do @echo %~nxai
- For each non-hidden file in the current folder, outputs the file attributes followed by the file name. In the string «%~nxai», uses the syntax described at #Percent tilde.
- for /f «usebackq tokens=*» %i in (`dir /b /a-d-h`) do @echo %~nxai
- As above, but using the backquote character (`) around the command to be executed.
- for /f «tokens=*» %i in (‘tasklist ^| sort ^& echo End’) do @echo %i
- Pipes and ampersands in the command to be executed must be escaped using caret (^).
Examples of redirection:
- (for %i in (1,2,3) do @echo %i) > anyoldtemp.txt
- To redirect the entire result of a for loop, place the entire loop inside brackets before redirecting. Otherwise, the redirection will tie to the body of the loop, so each new iteration of the body of the loop will override the results of the previous iterations.
- for %i in (1,2,3) do @echo %i > anyoldtemp.txt
- An example related to the one above. It shows the consequence of failing to put the loop inside brackets.
Continue: To jump to the next iteration of the loop and thus emulate the continue statement known from many languages, you can use goto provided you put the loop body in a subroutine, as shown in the following:
for %%i in (a b c) do call :for_body %%i exit /b :for_body echo 1 %1 goto :cont echo 2 %1 :cont exit /b
If you use goto directly inside the for loop, the use of goto breaks the loop bookkeeping. The following fails:
for %%i in (a b c) do ( echo 1 %%i goto :cont echo 2 %%i :cont echo 3 %%i )
Links:
- for at ss64.com
- for at Microsoft
- Rules for how CMD.EXE parses numbers by dbenham, dostips.com
Outputs or sets the command to be executed for a file type. See also ASSOC.
Examples:
- ftype
- Lists all associations of commands to be executed with file types, as, for example, ‘Perl=»C:\Perl\bin\perl.exe» «%1» %*’
- ftype | find «Excel.Sheet»
- Lists only associations whose display line contains «Excel.Sheet»
Links:
- ftype at ss64.com
- ftype at Microsoft
- Making Python scripts run on Windows without specifying “.py” extension at stackoverflow
Goes to a label.
An example:
goto :mylabel echo Hello 1 REM Hello 1 never gets printed. :mylabel echo Hello 2 goto :eof echo Hello 3 REM Hello 3 never gets printed. Eof is a virtual label standing for the end of file.
Goto within the body of a for loop makes cmd forget about the loop, even if the label is within the same loop body.
Links:
- goto at ss64.com
- goto at Microsoft
Conditionally executes a command. Documentation is available by entering IF /? to CMD prompt.
Available elementary tests:
- exist <filename>
- <string>==<string>
- <expression1> equ <expression2> — equals
- <expression1> neq <expression2> — not equal
- <expression1> lss <expression2> — less than
- <expression1> leq <expression2> — less than or equal
- <expression1> gtr <expression2> — greater than
- <expression1> geq <expression2> — greater than or equal
- defined <variable>
- errorlevel <number>
- cmdextversion <number>
To each elementary test, «not» can be applied. Apparently there are no operators like AND, OR, etc. to combine elementary tests.
The /I switch makes the == and equ comparisons ignore case.
An example:
if not exist %targetpath% ( echo Target path not found. exit /b )
Examples:
- if not 1 equ 0 echo Not equal
- if 1 equ 0 echo A & echo B
- Does nothing; both echo commands are subject to the condition.
- if not 1 equ 0 goto :mylabel
- if not a geq b echo Not greater
- if b geq a echo Greater
- if b geq A echo Greater in a case-insensitive comparison
- if B geq a echo Greater in a case-insensitive comparison
- if 0 equ 00 echo Numerical equality
- if not 0==00 echo String inequality
- if 01 geq 1 echo Numerical comparison
- if not «01» geq «1» echo String comparison
- if 1 equ 0 (echo Equal) else echo Unequal
- Notice the brackets around the positive then-part to make it work.
- if not a==A echo Case-sensitive inequality
- if /i a==A echo Case-insensitive equality
- if /i==/i echo This does not work
- if «/i»==»/i» echo Equal, using quotation marks to prevent the literal meaning of /i
Links:
- if at ss64.com
- if at Microsoft
Creates a new directory or directories. Has a synonym MKDIR; see also its antonym RD.
Examples:
- md Dir
- Creates one directory in the current directory.
- md Dir1 Dir2
- Creates two directories in the current directory.
- md «My Dir With Spaces»
- Creates a directory with a name containing spaces in the current directory.
Links:
- md at ss64.com
- md at Microsoft
A synonym for MD.
Makes a symbolic link or other type of link. Available since Windows Vista.
Links:
- mklink at ss64.com
- mklink at Microsoft
Moves files or directories between directories, or renames them. See also REN.
Examples:
- move File1.txt File2.txt
- Renames File1.txt to File2.txt, overwriting File2.txt if confirmed by the user or if run from a batch script.
- move File.txt Dir
- Moves File.txt file into Dir directory, assuming File.txt is a file and Dir is a directory; overwrites target file Dir\a.txt if conditions for overwriting are met.
- move Dir1 Dir2
- Renames directory Dir1 to Dir2, assuming Dir1 is a directory and Dir2 does not exist.
- move Dir1 Dir2
- Moves directory Dir1 into Dir2, resulting in existence of Dir2\Dir1, assuming both Dir1 and Dir2 are existing directories.
- move F:\File.txt
- Moves the file to the current directory.
- move F:\*.txt
- Moves the files located at F:\ and ending in dot txt into the current directory, assuming the current directory is not F:\.
Links:
- move at ss64.com
- move at Microsoft
Outputs or sets the value of the PATH environment variable. When outputting, includes «PATH=» at the beginning of the output.
Examples:
- path
- Outputs the PATH. An example output:
- PATH=C:\Windows\system32;C:\Windows;C:\Program Files\Python27
- Outputs the PATH. An example output:
- path C:\Users\Joe Hoe\Scripts;%path%
- Extends the path with C:\Users\Joe Hoe\Scripts, applying only to the process of the cmd.exe.
- path ;
- Empties the path.
- echo %path% | perl -pe «s/;/\n/g» | sort
- Shows the folders in the path sorted if you have perl installed.
Links:
- path at ss64.com
- path at Microsoft
Prompts the user and waits for a line of input to be entered.
Links:
- pause at SS64.com
- pause at Microsoft
Changes to the drive and directory popped from the directory stack. The directory stack is filled using the PUSHD command.
Links:
- popd at ss64.com
- popd at Microsoft
Can be used to change or reset the cmd.exe prompt. It sets the value of the PROMPT environment variable.
C:\>PROMPT MyPrompt$G MyPrompt>CD C:\ MyPrompt>PROMPT C:\>
The PROMPT command is used to set the prompt to «MyPrompt>». The CD shows that the current directory path is «C:\». Using PROMPT without any parameters sets the prompt back to the directory path.
Links:
- prompt at ss64.com
- prompt at Microsoft
Pushes the current directory onto the directory stack, making it available for the POPD command to retrieve, and, if executed with an argument, changes to the directory stated as the argument.
Links:
- pushd at ss64.com
- pushd at Microsoft
Removes directories. See also its synonym RMDIR and antonym MD. Per default, only empty directories can be removed. Also type «rd /?».
Examples:
- rd Dir1
- rd Dir1 Dir2
- rd «My Dir With Spaces»
- rd /s Dir1
- Removes the directory Dir1 including all the files and subdirectories in it, asking for confirmation once before proceeding with the removal. To delete files recursively in nested directories with a confirmation per file, use DEL with /s switch.
- rd /q /s Dir1
- Like above, but without asking for confirmation.
Links:
- rd at ss64.com
- rd at Microsoft
Renames files and directories.
Examples:
- ren filewithtpyo.txt filewithtypo.txt
- ren *.cxx *.cpp
Links:
- ren at ss64.com
- ren at Microsoft
- How does the Windows RENAME command interpret wildcards?, superuser.com
This is a synonym of REN command.
Used for remarks in batch files, preventing the content of the remark from being executed.
An example:
REM A remark that does not get executed echo Hello REM This remark gets displayed by echo echo Hello & REM This remark gets ignored as wished :: This sentence has been marked as a remark using double colon.
REM is typically placed at the beginning of a line. If placed behind a command, it does not work, unless preceded by an ampersand, as shown in the example above.
Double colon is an alternative to REM. It can cause trouble when used in the middle of sequences in parentheses, like those used in FOR loops. The double colon seems to be just a trick, a label that starts with a colon.
Links:
- rem at ss64.com
- rem at Microsoft
- Which comment style should I use in batch files?, stackoverflow.com
This is a synonym of RD.
Outputs or sets environment variables. With /P switch, it asks the user for input, storing the result in the variable. With /A switch, it performs simple arithmetic calculations, storing the result in the variable. With string assignments, spaces before and after the equality sign are usually avoided since they lead to usually unintended consequences: «set name = Peter» assigns to variable «name «, while «set name=Peter» assigns to variable «name». See also #Environment variables and #Calculation.
Examples:
- set
- Outputs a list of environment variables with their values, in the format of VAR=VALUE, a variable per line.
- set home
- Outputs a list of environment variables with their values for the variables whose names start with «home», case-insensitive, in the format of VAR=VALUE, a variable per line.
- set HOME
- As above; the match between the variable name prefix and the variable name is case insensitive.
- set myname=Joe Hoe
- Sets the variable to a new value.
- set mynumber=56
- Sets the variable to the string value of «56».
- set mynumber=
- Unsets the variable, removing it from variables. The equal sign (=) must be the final character; with any spaces after the equal sign, they become the new value of the variable.
- set home=%home%;C:\Program Files\My Bin Folder
- set /P user_input=Enter an integer:
- set /P firstline=< File.txt
- Sets the variable to the first line of the file. An equivalent of head -1 command from other operating systems.
- set /A result = 4 * ( 6 / 3 )
- Sets the result variable with the result of a calculation. See also #Calculation.
- set name = Peter
echo *%name %*- Sets the value of variable «name «, with ending space, to the value of » Peter», with leading space. The intent was probably to use «set name=Peter», with no separating spaces.
Links:
- set at ss64.com
- set at Microsoft
When used in a batch file, makes all further changes to environment variables local to the current batch file. When used outside of a batch file, does nothing. Can be ended using ENDLOCAL. Exiting a batch file automatically calls «end local». Can be used to create subprograms: see Functions.
Furthermore, can be used to enable delayed expansion like this: «setlocal EnableDelayedExpansion». Delayed expansion consists in the names of variables enclosed in exclamation marks being replaced with their values only after the execution reaches the location of their use rather than at an earlier point.
The following is an example of using delayed expansion in a script that prints the specified number of first lines of a file, providing some of the function of the command «head» known from other operating systems:
@echo off call :myhead 2 File.txt exit /b :: Function myhead :: =============== :: %1 - lines count, %2 - file name :myhead setlocal EnableDelayedExpansion set counter=1 for /f "tokens=*" %%i in (%2) do ( echo %%i set /a counter=!counter!+1 if !counter! gtr %1 exit /b ) exit /b
Links:
- setlocal at ss64.com
- EnableDelayedExpansion at ss64.com
- setlocal at Microsoft
Shifts the batch file arguments along, but does not affect %*. Thus, if %1=Hello 1, %2=Hello 2, and %3=Hello 3, then, after SHIFT, %1=Hello 2, and %2=Hello 3, but %* is «Hello 1» «Hello 2» «Hello 3».
Links:
- shift at ss64.com
- shift at Microsoft
Starts a program in new window, or opens a document. Uses an unclear algorithm to determine whether the first passed argument is a window title or a program to be executed; hypothesis: it uses the presence of quotes around the first argument as a hint that it is a window title.
Examples:
- start notepad.exe & echo «Done.»
- Starts notepad.exe, proceeding to the next command without waiting for finishing the started one. Keywords: asynchronous.
- start «notepad.exe»
- Launches a new console window with notepad.exe being its title, apparently an undesired outcome.
- start «» «C:\Program Files\Internet Explorer\iexplore.exe»
- Starts Internet Explorer. The empty «» passed as the first argument is the window title of a console that actually does not get opened, or at least not visibly so.
- start «C:\Program Files\Internet Explorer\iexplore.exe»
- Launches a new console window with «C:\Program Files\Internet Explorer\iexplore.exe» being its title, apparently an undesired outcome.
- start /wait notepad.exe & echo «Done.»
- Starts notepad.exe, waiting for it to end before proceeding.
- start /low notepad.exe & echo «Done.»
- As above, but starting the program with a low priority.
- start «» MyFile.xls
- Opens the document in the program assigned to open it.
- start
- Starts a new console (command-line window) in the same current folder.
- start .
- Opens the current folder in Windows Explorer.
- start ..
- Opens the parent folder in Windows Explorer.
- start «» «mailto:»
- Starts the application for writing a new email.
- start «» «mailto:joe.hoe@hoemail.com?subject=Notification&body=Hello Joe, I’d like to…»
- Starts the application for writing a new email, specifying the to, subject and body of the new email.
- start «» «mailto:joe.hoe@hoemail.com?subject=Notification&body=Hello Joe,%0a%0aI’d like to…»
- As above, with newlines entered as %0a.
- start /b TODO:example-application-where-this-is-useful
- Starts the application without opening a new console window, redirecting the output to the console from which the start command was called.
Links:
- start at ss64.com
- start at Microsoft
- How to use command line switches to create a pre-addressed e-mail message in Outlook, support.microsoft.com
Ouputs or sets the system time. See also #DATE and TIME variable in #Special variable names.
Examples
- time /t
- Outputs the system time in HH:MM format, with no seconds and milliseconds. An example output: 09:19.
- time
- Outputs the system time in a locale-specific format possibly featuring seconds and hundredths of seconds and asks for a new time to set; the time is preceded by a locale-specific message, usually a translation of «Current time:». Thus, the output format differs from the one of «time /t».
- echo %time%
- Outputs the current time using the special variable TIME, in a locale-dependent format featuring hours, minutes, seconds and possibly hundredths of seconds. An example output for one locale: 9:19:31.55.
- echo %time% & timeout 1 >nul & echo,|time
- Outputs time before and after the command in the middle, here timeout 1. Can be used to measure execution time of the sequence in the middle; keywords: how long does it take.
Links:
- time at ss64.com
- time at Microsoft
Sets the title displayed in the console window.
Links:
- title at ss64.com
- title at Microsoft
Prints the content of a file or files to the output.
Examples:
- type filename.txt
- type a.txt b.txt
- type *.txt
- type NUL > tmp.txt
- Create an empty file (blank file).
Links:
- type at ss64.com
- type at Microsoft
Shows the command processor or operating system version.
C:\>VER Microsoft Windows XP [Version 5.1.2600] C:\>
Some version strings:
- Microsoft Windows [Version 5.1.2600]
- For Windows XP
- Microsoft Windows [Version 6.0.6000]
- For Windows Vista
- …
The word «version» appears localized.
Links:
- ver at ss64.com
- ver at Microsoft
- Operating System Version at Microsoft
- List of Microsoft Windows versions, wikipedia.org
- Windows Build Numbers, eddiejackson.net
- mxpv/windows_build_numbers.txt, gist.github.com
Sets or clears the setting to verify whether COPY files etc. are written correctly.
Links:
- verify at ss64.com
- verify at Microsoft
Outputs volume labels.
Links:
- vol at ss64.com
- vol at Microsoft
External commands available to Windows command interpreter are separate executable program files, supplied with the operating system by Microsoft, or bundled as standard with the third-party command interpreters. By replacing the program files, the meanings and functions of these commands can be changed.
Many, but not all, external commands support the «/?» convention, causing them to write on-line usage information to their standard output and then to exit with a status code of 0.
Outputs or changes items in the address resolution protocol cache, which maps IP addresses to physical addresses.
Links:
- arp at ss64.com
- at arp Microsoft
Schedules a program to be run at a certain time. See also SCHTASKS.
Links:
- at at ss64.com
- at at Microsoft
Outputs or sets file attributes. With no arguments, it outputs the attributes of all files in the current directory. With no attribute modification instructions, it outputs the attributes of the files and directories that match the given search wildcard specifications. Similar to chmod of other operating systems.
Modification instructions:
- To add an attribute, attach a ‘+’ in front of its letter.
- To remove an attribute, attach a ‘-‘ in front of its letter
- Attributes:
- A — Archived
- H — Hidden
- S — System
- R — Read-only
- …and possibly others.
Examples:
- attrib
- Outputs the attributes of all files in the current directory.
- attrib File.txt
- Outputs the attributes of the file.
- attrib +r File.txt
- Adds the «Read-only» attribute to the file.
- attrib -a File.txt
- Removes the «Archived» attribute from the file.
- attrib -a +r File.txt
- Removes the «Archived» attribute and adds the «Read-only» attribute to the file.
- attrib +r *.txt
- Acts on a set of files.
- attrib /S +r *.txt
- Acts recursively in subdirectories.
For more, type «attrib /?».
Links:
- attrib at ss64.com
- attrib at Microsoft
(Not in XP). Edits Boot Configuration Data (BCD) files. For more, type «bcdedit /?».
Links:
- bcdedit at ss64.com
- at Microsoft
Outputs or changes discretionary access control lists (DACLs). See also ICACLS. For more, type «cacls /?».
Links:
- cacls at ss64.com
- cacls at Microsoft
Outputs or sets the active code page number. For more, type «chcp /?».
Links:
- chcp at ss64.com
- chcp at Microsoft
Checks disks for disk problems, listing them and repairing them if wished. For more, type «chkdsk /?».
Links:
- chkdsk at ss64.com
- chkdsk at Microsoft
Shows or sets whether system checking should be run when the computer is started. The system checking is done using Autochk.exe. The «NTFS» part of the command name is misleading, since the command works not only with NTFS file system but also with FAT and FAT32 file systems. For more, type «chkntfs /?».
Links:
- chkntfs at ss64.com
- chkntfs at Microsoft
Lets the user choose one of multiple options by pressing a single key, and sets the error level as per the chosen option. Absent in Windows 2000 and Windows XP, it was reintroduced in Windows Vista, and has remained in Windows 7 and 8.
Examples:
- choice /m «Do you agree»
- Presents the user with a yes/no question, setting the error level to 1 for yes and to 2 for no. If the user presses Control + C, the error level is 0.
- choice /c rgb /m «Which color do you prefer»
- Presents the user with a question, and indicates the letters for the user. Responds to user pressing r, g or b, setting the error level to 1, 2 or 3.
An alternative is «set /p»; see SET.
Links:
- choice at ss64.com
- choice at Microsoft
Shows the encryption state, encrypts or decrypts folders on a NTFS volume.
Links:
- cipher at ss64.com
- cipher at Microsoft
(Not in XP, or make a copy from Server 2003) Places the piped input to the clipboard.
Examples:
- set | clip
- Places the listing of environment variables to the clipboard.
- clip < File1.txt
- Places the content of File1.txt to the clipboard.
Links:
- clip at ss64.com
- clip at Microsoft
Invokes another instance of Microsoft’s CMD.
Links:
- cmd at ss64.com
- cmd at Microsoft
Compares files. See also FC.
Links:
- comp at ss64.com
- comp at Microsoft
Shows or changes the compression of files or folders on NTFS partitions.
Links:
- compact at Microsoft
Converts a volume from FAT16 or FAT32 file system to NTFS file system.
Links:
- convert at ss64.com
- convert at Microsoft
Allows to interactively examine file and memory contents in assembly language, hexadecimal or ASCII. Available in 32-bit Windows including Windows 7; the availability in 64-bit Windows is unclear. In modern Windows, useful as a quick hack to view hex content of a file. Keywords: hex dump, hexdump, hexadecimal dump, view hex, view hexadecimal, disassembler.
Debug offers its own command line. Once on its command like, type «?» to find about debug commands.
To view hex of a file, invoke debug.exe with the file name as a parameter, and then repeatedly type «d» followed by enter on the debug command line.
Limitations:
- Being a DOS program, debug chokes on long file names. Use dir /x to find the 8.3 file name, and apply debug on that one.
- Debug cannot view larger files.
Links:
- Debug for Windows XP at TechNet / Microsoft Docs
- Debug for MS-DOS at TechNet / Microsoft Docs
- W:Debug (command)
Compares the content of two floppies.
Links:
- diskcomp at ss64.com
- diskcomp at Microsoft
Copies the content of one floppy to another.
Links:
- diskcopy at ss64.com
- diskcopy at Microsoft
Shows and configures the properties of disk partitions.
Links:
- diskpart at ss64.com
- diskpart at Microsoft, for XP
- diskpart at Microsoft
Above all, creates macros known from other operating systems as aliases. Moreover, provides functions related to command history, and enhanced command-line editing. Macros are an alternative to very short batch scripts.
Macro-related examples:
- doskey da=dir /s /b
- Creates a single macro called «da»
- doskey np=notepad $1
- Creates a single macro that passes its first argument to notepad.
- doskey /macrofile=doskeymacros.txt
- Loads macro definitions from a file.
- doskey /macros
- Lists all defined macros with their definitions.
- doskey /macros | find «da»
- Lists all macro definitions that contain «da» as a substring; see also FIND.
Command history-related examples:
- doskey /history
- Lists the complete command history.
- doskey /history | find «dir»
- Lists each line of command history that contains «dir» as a substring
- doskey /listsize=100
- Sets the size of command history to 100.
To get help on doskey from command line, type «doskey /?».
Links:
- doskey at ss64.com
- doskey at Microsoft
Shows all installed device drivers and their properties.
Links:
- driverquery at ss64.com
- driverquery at Microsoft
Extracts files from compressed .cab cabinet files. See also #MAKECAB.
Links:
- expand at ss64.com
- expand at Microsoft
Compares files, displaying the differences in their content in a peculiar way.
Examples:
- fc File1.txt File2.txt >NUL && Echo Same || echo Different or error
- Detects difference using the error level of fc. The error level of zero means the files are the same; non-zero can mean the files differ but also that one of the files does not exist.
Links:
- fc at ss64.com
- fc at Microsoft
Searches for a string in files or input, outputting matching lines. Unlike FINDSTR, it cannot search folders recursively, cannot search for a regular expression, requires quotation marks around the sought string, and treats space literally rather than as a logical or.
Examples:
- find «(object» *.txt
- dir /S /B | find «receipt»
- dir /S /B | find /I /V «receipt»
- Prints all non-matching lines in the output of the dir command, ignoring letter case.
- find /C «inlined» *.h
- Instead of outputting the matching lines, outputs their count. If more than one file is searched, outputs one count number per file preceded with a series of dashes followed by the file name; does not output the total number of matching lines in all files.
- find /C /V «» < file.txt
- Outputs the number of lines AKA line count in «file.txt». Does the job of «wc -l» of other operating systems. Works by treating «» as a string not found on the lines. The use of redirection prevents the file name from being output before the number of lines.
- type file.txt | find /C /V «»
- Like the above, with a different syntax.
- type *.txt 2>NUL | find /C /V «»
- Outputs the sum of line counts of the files ending in «.txt» in the current folder. The «2>NUL» is a redirection of standard error that removes the names of files followed by empty lines from the output.
- find «Schönheit» *.txt
- If run from a batch file saved in unicode UTF-8 encoding, searches for the search term «Schönheit» in UTF-8 encoded *.txt files. For this to work, the batch file must not contain the byte order mark written by Notepad when saving in UTF-8. Notepad++ is an example of a program that lets you write UTF-8 encoded plain text files without byte order mark. While this works with find command, it does not work with #FINDSTR.
- find «Copyright» C:\Windows\system32\a*.exe
- Works with binary files no less than text files.
Links:
- find at ss64.com
- find at Microsoft
Searches for regular expressions or text strings in files. Does some of the job of «grep» command known from other operating systems, but is much more limited in the regular expressions it supports.
Treats space in a regular expression as a disjunction AKA logical or unless prevented with /c option.
Examples:
- findstr /s «[0-9][0-9].*[0-9][0-9]» *.h *.cpp
- Searches recursively all files whose name ends with dot h or dot cpp, printing only lines that contain two consecutive decimal digits followed by anything followed by two consecutive decimal digits.
- findstr «a.*b a.*c» File.txt
- Outputs all lines in File.txt that match any of the two regular expressions separated by the space. Thus, the effect is one of logical or on regular expressions.
- echo world | findstr «hello wo.ld»
- Does not match. Since the 1st item before the space does not look like a regex, findstr treats the whole search term as a plain search term.
- echo world | findstr /r «hello wo.ld»
- Matches. The use of /r forces regex treatment.
- findstr /r /c:»ID: *[0-9]*» File.txt
- Outputs all lines in File.txt that match the single regular expression containing a space. The use of /c prevents the space from being treated as a logical or. The use of /r switches the regular expression treatment on, which was disabled by default by the use of /c. To test this, try the following:
- echo ID: 12|findstr /r /c:»ID: *[0-9]*$»
- Matches.
- echo ID: 12|findstr /c:»ID: *[0-9]*$»
- Does not match, as the search string is not interpreted as a regular expression.
- echo ID: abc|findstr «ID: *[0-9]*$»
- Matches despite the output of echo failing to match the complete regular expression: the search is interpreted as one for lines matching «ID:» or «*[0-9]*$».
- echo ID: 12|findstr /r /c:»ID: *[0-9]*$»
- Outputs all lines in File.txt that match the single regular expression containing a space. The use of /c prevents the space from being treated as a logical or. The use of /r switches the regular expression treatment on, which was disabled by default by the use of /c. To test this, try the following:
- findstr /ric:»id: *[0-9]*» File.txt
- Does the same as the previous example, but in a case-insensitive manner.
- While findstr enables this sort of accumulation of switches behind a single «/», this is not possible with any command. For instance, «dir /bs» does not work, while «dir /b /s» does.
- To test this, try the following:
- echo ID: 12|findstr /ric:»id: *[0-9]*$»
- echo ID: ab|findstr /ric:»id: *[0-9]*$»
- findstr /msric:»id: *[0-9]*» *.txt
- Like above, but recursively for all files per /s, displaying only matching files rather than matching lines per /m.
- echo hel lo | findstr /c:»hel lo» /c:world
- /c switch can be used multiple times to create logical or.
- echo \hello\ | findstr «\hello\»
- Does not match. Backslash before quotation marks and multiple other characters acts as an escape; thus, \» matches «.
- echo \hello\ | findstr «\\hello\\»
- Matches. Double backslash passed to findstr stands for a single backslash.
- echo \hello\ | findstr \hello\
- Matches. None of the single backslashes passed to findstr is followed by a character on which the backslash acts as an escape.
- echo ^»hey | findstr \^»hey | more
- To search for a quote (quotation mark), you need to escape it two times: once for the shell using caret (^), and once for findstr using backslash (\).
- echo ^»hey | findstr ^»\^»hey there^» | more
- To search for a quote and have the search term enclosed in quotes as well, the enclosing quotes need to be escaped for the shell using caret (^).
- echo //comment line | findstr \//
- If forward slash (/) is the 1st character in the search term, it needs to be escaped with a backslash (\). The escaping is needed even if the search term is enclosed in quotes.
- findstr /f:FileList.txt def.*():
- Search in the files stated in FileList.txt, one file per line. File names in FileList.txt can contain spaces and do not need to be surrounded with quotation marks for this to work.
- findstr /g:SearchTermsFile.txt *.txt
- Search for the search terms found in SearchTermsFile.txt, one search term per line. A space does not serve to separate two search terms; rather, each line is a complete search term. A line is matched if at least one of the search terms matches. If the first search term looks like a regex, the search will be a regex one, but if it looks like a plain search term, the whole search will be a plain one even if 2nd or later search terms look like regex.
- findstr /xlg:File1.txt File2.txt
- Outputs set intersection: lines present in both files.
- findstr /xlvg:File2.txt File1.txt
- Outputs set difference: File1.txt — File2.txt.
- findstr /m Microsoft C:\Windows\system32\*.com
- Works with binary files no less than text files.
Limitations of the regular expressions of «findstr», as compared to «grep»:
- No support of groups — «\(«, «\)».
- No support of greedy iterators — «*?».
- No support of «zero or one of the previous» — «?».
- And more.
Other limitations: There is a variety of limitations and strange behaviors as documented at
What are the undocumented features and limitations of the Windows FINDSTR command?.
Bugs:
- echo bb|findstr «bb baaaa»
- Does not find anything in multiple Windows versions, but it should.
Also consider typing «findstr /?».
Links:
- findstr at ss64.com
- findstr at Microsoft
- What are the undocumented features and limitations of the Windows FINDSTR command? at StackOverflow
Finds files by their modification date and file name pattern, and executes a command for each found file. Is very limited, especially compared to the find command of other operating systems. Available since Windows Vista. For more, type «forfiles /?».
Examples:
- forfiles /s /d 06/10/2015 /c «cmd /c echo @fdate @path»
- For each file in the current folder and its subfolders modified on 10 June 2015 or later, outputs the file modification date and full file path. The date format after /d is locale specific. Thus, allows to find most recently modified files. Keywords: most recently changed files.
- forfiles /m *.txt /s /d 06/10/2015 /c «cmd /c echo @fdate @path»
- As above, but only for files ending in .txt.
Links:
- forfiles at ss64.com
- forfiles at Microsoft
forfiles /?
Formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk. To be used with great caution.
Links:
- format at ss64.com
- format at Microsoft
A powerful tool performing actions related to FAT and NTFS file systems, to be ideally only used by powerusers with an extensive knowledge of the operating systems.
Links:
- fsutil at ss64.com
- fsutil at Microsoft
- Fsutil: behavior
- Fsutil: dirty
- Fsutil: file
- Fsutil: fsinfo
- Fsutil: hardlink
- Fsutil: objectid
- Fsutil: quota
- Fsutil: reparsepoint
- Fsutil: sparse
- Fsutil: usn
- Fsutil: volume
Outputs group policy settings and more for a user or a computer.
Links:
- gpresult at ss64.com
- gpresult at Microsoft
- Wikipedia:Group Policy
Enables the display of an extended character set in graphics mode. For more, type «graftabl /?».
Links:
- graftabl at Microsoft
Shows command help.
Examples:
- help
- Shows the list of Windows-supplied commands.
- help copy
- Shows the help for COPY command, also available by typing «copy /?».
Links:
- help at ss64.com
- help at Microsoft
(Not in XP) Shows or changes discretionary access control lists (DACLs) of files or folders. See also CACLS. Fore more, type «icacls /?».
Links:
- icacls at ss64.com
- icacls at Microsoft
Outputs Windows IP Configuration. Shows configuration by connection and the name of that connection (i.e. Ethernet adapter Local Area Connection)
Below that the specific info pertaining to that connection is displayed such as DNS suffix and ip address and subnet mask.
Links:
- ipconfig at ss64.com
- ipconfig at Microsoft
Adds, sets or removes a disk label.
Links:
- label at ss64.com
- label at Microsoft
Places files into compressed .cab cabinet file. See also #EXPAND.
Links:
- makecab at ss64.com
- makecab at Microsoft
A multi-purpose command to display device status, configure ports and devices, and more.
Examples:
- mode
- Outputs status and configuration of all devices, such as com3 and con.
- mode con
- Outputs status and configuration of con device, the console in which the command interpreter is running.
- mode con cols=120 lines=20
- Sets the number of columns and lines for the current console, resulting in window resizing, and clears the screen. The setting does not affect new console instances. Keywords: wide screen, wide window, screen size, window size, resize screen, resize window.
- mode 120, 20
- As above: Sets the number of columns (120) and lines (20), resulting in window resizing, and clears the screen.
- mode con cols=120
- Sets the number of columns for the current console, resulting in window resizing, and clears the screen. It seems to change the number of visible lines as well, but the total lines count of the console buffer seems unchanged.
- mode 120
- As above: Sets the number of columns.
- mode con cp
- Outputs the current code page of the console.
- mode con cp select=850
- Sets the current code page of the console. For a list of code pages, see the linked Microsoft documentation below.
- mode con rate=31 delay=1
- Sets the rate and delay for repeated entry of a character while a key is held pressed, of the console. The lower the rate, the fewer repetitions per second.
Links:
- mode at ss64.com
- mode at Microsoft
Outputs the contents of a file or files, one screen at a time. When redirected to a file, performs some conversions, also depending on the used switches.
Examples:
- more Test.txt
- more *.txt
- grep -i sought.*string Source.txt | more /p >Out.txt
- Taking the output of a non-Windows grep command that produces line breaks consisting solely of LF character without CR character, converts LF line breaks to CR-LF line breaks. CR-LF newlines are also known as DOS line breaks, Windows line breaks, DOS newlines, Windows newlines, and CR/LF line endings,as opposed to LF line breaks used by some other operating systems.
- In some setups, seems to output gibberish if the input contains LF line breaks and tab characters at the same time.
- In some setups, for the conversion, /p may be unneeded. Thus, «more» would convert the line breaks even without /p.
- more /t4 Source.txt >Target.txt
- Converts tab characters to 4 spaces.
- In some setups, tab conversion takes place automatically, even without the /t switch. If so, it is per default to 8 spaces.
Switch /e:
- The online documentation for «more» in Windows XP and Windows Vista does not mention the switch.
- The switch /e is mentioned in «more /?» at least in Windows XP and Windows Vista.
- Per «more /?», the switch is supposed to enable extended features listed at the end of «more /?» help such as showing the current row on pressing «=». However, in Windows XP and Windows Vista, that seems to be enabled by default even without /e.
- Hypothesis: In Windows XP and Windows Vista, /e does not do anything; it is present for compatibility reasons.
Links:
- more at ss64.com
- more at Microsoft, Windows XP
- more at Microsoft, Windows Server 2008, Windows Vista
Provides various network services, depending on the command used. Available variants per command:
- net accounts
- net computer
- net config
- net continue
- net file
- net group
- net help
- net helpmsg
- net localgroup
- net name
- net pause
- net print
- net send
- net session
- net share
- net start
- net statistics
- net stop
- net time
- net use
- net user
- net view
Links:
- net at ss64.com
- net services overview at Microsoft, Windows XP
- net computer at Microsoft
- net group at Microsoft
- net localgroup at Microsoft
- net print at Microsoft
- net session at Microsoft
- net share at Microsoft
- net use at Microsoft
- net user at Microsoft
- net view at Microsoft
Performs actions pertaining to open files, especially those opened by other users over the network. The actions involve querying, displaying, and disconnecting. For more, type «openfiles /?».
Links:
- openfiles at ss64.com
- openfiles at Microsoft
Syntax:
- PING /?
- PING address
- PING hostname
Send ICMP/IP «echo» packets over the network to the designated address (or the first IP address that the designated hostname maps to via name lookup) and print all responses received.
Examples:
- ping en.wikibooks.org
- ping 91.198.174.192
- ping http://en.wikibooks.org/
- Does not work.
Links:
- ping at ss64.com
- ping at Microsoft
Recovers as much information as it can from damaged files on a defective disk.
Links:
- recover at ss64.com
- recover at Microsoft
Queries or modifies Windows registry.
The first argument is one of the following commands: query, add, delete, copy, save, load, unload, restore, compare, export, import, and flags. To learn more about a command, follow it by /?, like reg query /?.
Links:
- reg at ss64.com
- reg at Microsoft
Replaces files in the destination folder with same-named files in the source folder.
Links:
- replace at ss64.com
- replace at Microsoft
(Not in XP) Copies files and folders. See also XCOPY and COPY.
Examples:
- robocopy /s C:\Windows\system C:\Windows-2\system *.dll
- Copies all files ending in .dll from one directory to another, replicating the nested directory structure.
Links:
- robocopy at ss64.com
- robocopy at Microsoft
Runs a function available from a DLL. The available DLLs and their functions differ among Windows versions.
Examples:
- rundll32 sysdm.cpl,EditEnvironmentVariables
- In some Windows versions, opens the dialog for editing environment variables.
Links:
- rundll32 at ss64.com
- at Microsoft
- rundll at robvanderwoude.com
- dx21.com — lists rundll32 examples
Controls Windows services, supporting starting, stopping, querying and more. Windows services are process-like things. A Windows service is either hosted in its own process or it is hosted in an instance of svchost.exe process, often with multiple services in the same instance. Processor time use of a particular service can be found using freely downloadable Process Explorer from Sysinternals, by going to properties of a service and then Threads tab. Another command capable of controlling services is NET. TASKLIST can list hosted services using /svc switch.
Examples:
- sc start wuauserv
- Starts wuauserv service.
- sc stop wuauserv
- sc query wuauserv
- sc query
- Outputs information about all services.
- sc config SysMain start= disabled
- Make sure SysMain service is disabled after start. SysMain is the SuperFetch service, causing repeated harddrive activity by trying to guess which programs to load into RAM in case they will be used, and loading them. Notice the mandatory lack of space before = and the mandatory space after =.
Links:
- sc at ss64.com
- Windows 7 Services at ss64.com
- sc at Microsoft
Schedules a program to be run at a certain time, more powerful than AT.
Links:
- schtasks at ss64.com
- schtasks at Microsoft
Like SET, but affecting the whole machine rather than the current console or process. Not available in Windows XP; available in Windows Vista and later.
Links:
- setx at ss64.com
- setx at Microsoft, Windows Server 2008, Windows Vista
Shuts down a computer, or logs off the current user.
Examples:
- shutdown /s
- Shuts down the computer.
- shutdown /s /t 0
- Shuts down the computer with zero delay.
- shutdown /l
- Logs off the current user.
Links:
- shutdown at ss64.com
- shutdown at Microsoft
Sorts alphabetically, from A to Z or Z to A, case insensitive. Cannot sort numerically: if the input contains one integer per line, «12» comes before «9».
Examples:
- sort File.txt
- Outputs the sorted content of File.txt.
- sort /r File.txt
- Sorts in reverse order, Z to A.
- dir /b | sort
Links:
- sort at ss64.com
- sort at Microsoft
Assigns a drive letter to a local folder, outputs current assignments, or removes an assignment.
Examples:
- subst p: .
- Assigns p: to the current folder.
- subst
- Outputs all assignments previously made using subst.
- subst /d p:
- Removes p: assignment.
Links:
- subst at ss64.com
- subst at Microsoft
Shows configuration of a computer and its operating system.
Links:
- systeminfo at ss64.com
- systeminfo at Microsoft
Ends one or more tasks.
Examples:
- taskkill /im AcroRd32.exe
- Ends all process with the name «AcroRd32.exe»; thus, ends all open instances of Acrobat Reader. The name can be found using tasklist.
- taskkill /f /im AcroRd32.exe
- As above, but forced. Succeeds in ending some processes that do not get ended without /f.
- tasklist | find «notepad»
taskkill /PID 5792
- Ends the process AKA task with process ID (PID) of 5792; the assumption is you have found the PID using tasklist.
Links:
- taskkill at ss64.com
- taskkill at Microsoft
Lists tasks, including task name and process id (PID).
Examples:
- tasklist | sort
- tasklist | find «AcroRd»
- tasklist | find /C «chrome.exe»
- Outputs the number of tasks named «chrome.exe», belonging to Google Chrome browser.
- tasklist /svc | findstr svchost
- Outputs Windows services hosted in svchost.exe processes alongside the usual information abot the process.
Links:
- tasklist at ss64.com
- tasklist at Microsoft
Waits a specified number of seconds, displaying the number of remaining seconds as time passes, allowing the user to interrupt the waiting by pressing a key. Also known as delay or sleep. Available in Windows Vista and later.
Examples:
- timeout /t 5
- Waits for five seconds, allowing the user to cancel the waiting by pressing a key.
- timeout /t 5 /nobreak
- Waits for five seconds, ignoring user input other than Control + C.
- timeout /t 5 /nobreak >nul
- As above, but with no output.
Workaround in Windows XP:
- ping -n 6 127.0.0.1 >nul
- Waits for five seconds; the number after -n is the number of seconds to wait plus 1.
Perl-based workaround in Windows XP, requiring Perl installed:
- perl -e «sleep 5»
- Waits for 5 seconds.
Links:
- timeout at ss64.com
- timeout at Microsoft
- How to wait in a batch script? at stackoverflow.com
- Sleeping in a batch file at stackoverflow.com
Outputs a tree of all subdirectories of the current directory to any level of recursion or depth. If used with /F switch, outputs not only subdirectories but also files.
Examples:
- tree
- tree /f
- Includes files in the listing, in addition to directories.
- tree /f /a
- As above, but uses 7-bit ASCII characters including «+», «-» and \» to draw the tree.
A snippet of a tree using 8-bit ASCII characters:
├───winevt │ ├───Logs │ └───TraceFormat ├───winrm
A snippet of a tree using 7-bit ASCII characters:
+---winevt | +---Logs | \---TraceFormat +---winrm
Links:
- tree at Microsoft
Outputs one or more locations of a file or a file name pattern, where the file or pattern does not need to state the extension if it listed in PATHEXT, such as .exe. Searches in the current directory and in the PATH by default. Does some of the job of «which» command of some other operating systems, but is more flexible.
Available on Windows 2003, Windows Vista, Windows 7, and later; not available on Windows XP. An alternative to be used with Windows XP is in the examples below.
Does not find internal commands, as there are no dot exe files for them to match.
Examples:
- where find
- Outputs the location of the find command, possibly «C:\Windows\System32\find.exe». The .exe extension does not need to be specified as long as it is listed in PATHEXT, which it is by default.
- If there are more find commands in the path, outputs paths to both. In some situations, it can output the following:
C:\Windows\System32\find.exe
C:\Program Files\GnuWin32\bin\find.exe
- for %i in (find.exe) do @echo %~$PATH:i
- Outputs the location of «find.exe» on Windows XP. The name has to include «.exe», unlike with the where command.
- where /r . Tasks*
- Searches for files whose name matches «Task*» recursively from the current folder. Similar to «dir /b /s Tasks*». The /r switch disables search in the folders in PATH.
- where *.bat
- Outputs all .bat files in the current directory and in the directories that are in PATH. Thus, outputs all .bat files that you can run without entering their full path.
- where ls*.bat
- As above, constraining also the beginning of the name of the .bat files.
- where ls*
- As above, but with no constraint on the extension. Finds lsdisks.bat, lsmice.pl, and lsmnts.py if in the current directory or in the path.
- where *.exe *.com | more
- Outputs countless .exe and .com files in the path and in the current folder, including those in C:\Windows\System32.
- where $path:*.bat
- Outputs .bat files in the path but not those in the current folder unless the current folder is in PATH. Instead of path, another environment variable containing a list of directories can be used.
- where $windir:*.exe
- Outputs .exe files found in the folder stated in WINDIR environment variable.
- where $path:*.bat $windir:*.exe
- A combination is possible. Outputs all files matching either of the two queries.
- where /q *.bat && echo Found
- Suppresses both standard and error output, but sets the error level, enabling testing on it. The error level is set either way, with or without /q.
Links:
- where at ss64.com
- where at Microsoft
- Is there an equivalent of ‘which’ on windows?
Starts Windows Management Instrumentation Command-line (WMIC), or with arguments given, passes the arguments as commands to WMIC. Not in Windows XP Home. For more, type «wmic /?».
Examples:
- wmic logicaldisk get caption,description
- Lists drives (disks) accessible under a drive letter, whether local hard drives, CD-ROM drives, removable flash drives, network drives or drives created using #SUBST.
- wmic logicaldisk get /format:list
- Outputs all properties of «logicaldisk» object, one property per separate line.
- wmic logicaldisk get /format:csv
- wmic
Control + C- Enters wmic and then interrupts it. A side effect is that the console buffer becomes very wide, and the screen becomes horizontally resizable with the mouse as a consequence. This is the result of wmic setting a high number of columns of the console, which you can verify using mode con. You can achieve a similar result by typing mode 1500. See also #MODE.
- wmic datafile where name=»C:\\Windows\\System32\\cmd.exe» get Version /value
- Outputs the version of the cmd.exe, which should be close to the Windows version.
- wmic os get TotalVisibleMemorySize
- Outputs total physical memory size.
- wmic os get TotalVirtualMemorySize
- Outputs total virtual memory size.
- wmic os get /format:list
- Outputs all properties of «os» object, one property per separate line.
Links:
- wmic at ss64.com
- wmic at Microsoft
Copies files and directories in a more advanced way than COPY, deprecated in Windows Vista and later in favor of ROBOCOPY. Type xcopy /? to learn more, including countless options.
Examples:
- xcopy C:\Windows\system
- Copies all files, but not files in nested folders, from the source folder («C:\Windows\system») to the current folder.
- xcopy /s /i C:\Windows\system C:\Windows-2\system
- Copies all files and folders to any nesting depth (via «/s») from the source folder («C:\Windows\system») to «C:\Windows-2\system», creating «Windows-2\system» if it does not exist (via «/i»).
- xcopy /s /i /d:09-01-2014 C:\Windows\system C:\Windows-2\system
- As above, but copies only files changed on 1 September 2014 or later. Notice the use of the month-first convention even if you are on a non-US locale of Windows.
- xcopy /L /s /i /d:09-01-2014 C:\Windows\system C:\Windows-2\system
- As above, but in a test mode via /L (list-only, output-only, display-only). Thus, does not do any actual copying, merely lists what would be copied.
- xcopy /s /i C:\Windows\system\*.dll C:\Windows-2\system
- As one of the examples above, but copies only files ending in .dll, including those in nested folders.
Links:
- xcopy at ss64.com
- xcopy at Microsoft
- PowerShell — a modern technology for scripting Windows operating systems
- VBScript Programming — a legacy Windows scripting technology whose syntax resembles Visual Basic
- Windows CMD Commands at ss64.com — licensed under Creative Commons Attribution-Non-Commercial-Share Alike 2.0 UK: England & Wales[1], and thus incompatible with CC-BY-SA used by Wikibooks
- Windows XP — Command-line reference A-Z at microsoft.com
- Windows Server 2008R2 — Command-Line Reference at microsoft.com
- Windows Server 2012R2 — Command-Line Reference at microsoft.com
- Windows Server 2016 — Windows Commands at microsoft.com
- The FreeDOS HTML Help at fdos.org — a hypertext help system for FreeDOS commands, written in 2003/2004, available under the GNU Free Documentation License
- Category:Batch File, rosettacode.org
- Cmd.exe, wikipedia.org
- Batch file, wikipedia.org
Command
Description
Append
The append command can be used by programs to open files in another directory as if they were located in the current directory. The append command is available in MS-DOS as well as in all 32-bit versions of Windows. The append command is not available in 64-bit versions of Windows.
Arp
The arp command is used to display or change entries in the ARP cache. The arp command is available in all versions of Windows.
Assoc
The assoc command is used to display or change the file type associated with a particular file extension. The assoc command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
At
The at command is used to schedule commands and other programs to run at a specific date and time. The at command is available in Windows 7, Windows Vista, and Windows XP. Beginning in Windows 8, command line task scheduling should instead be completed with the schtasks command.
Atmadm
The atmadm command is used to display information related to asynchronous transfer mode (ATM) connections on the system. The atmadm command is available in Windows XP. Support for ATM was removed beginning in Windows Vista, making the atmadm command unnecessary.
Attrib
The attrib command is used to change the attributes of a single file or a directory. The attrib command is available in all versions of Windows, as well as in MS-DOS.
Auditpol
The auditpol command is used to display or change audit policies. The auditpol command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Bcdboot
The bcdboot command is used to copy boot files to the system partition and to create a new system BCD store. The bcdboot command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Bcdedit
The bcdedit command is used to view or make changes to Boot Configuration Data. The bcdedit command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. The bcdedit command replaced the bootcfg command beginning in Windows Vista.
Bdehdcfg
The bdehdcfg command is used to prepare a hard drive for BitLocker Drive Encryption. The bdehdcfg command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Bitsadmin
The bitsadmin command is used to create, manage, and monitor download and upload jobs. The bitsadmin command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. While the bitsadmin command is available in those versions of Windows, it is being phased out—the BITS PowerShell cmdlets should be used instead.
Bootcfg
The bootcfg command is used to build, modify, or view the contents of the boot.ini file, a hidden file that is used to identify in what folder, on which partition, and on which hard drive Windows is located. The bootcfg command is available in Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The bootcfg command was replaced by the bcdedit command beginning in Windows Vista. Bootcfg is still available in Windows 10, 8, 7, and Vista, but it serves no real value since boot.ini is not used in these operating systems.
Bootsect
The bootsect command is used to configure the master boot code to one compatible with BOOTMGR (Vista and later) or NTLDR (XP and earlier). The bootsect command is available in Windows 11, Windows 10, and Windows 8. The bootsect command is also available in Windows 7 and Windows Vista but only from the Command Prompt available in System Recovery Options.
Break
The break command sets or clears extended CTRL+C checking on DOS systems. The break command is available in all versions of Windows, as well as in MS-DOS. The break command is available in Windows XP and later versions of Windows to provide compatibility with MS-DOS files but it has no effect in Windows itself.
Cacls
The cacls command is used to display or change access control lists of files. The cacls command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The cacls command is being phased out in favor of the icacls command, which should be used instead in all versions of Windows after Windows XP.
Call
The call command is used to run a script or batch program from within another script or batch program. The call command is available in all versions of Windows, as well as in MS-DOS. The call command has no effect outside of a script or batch file. In other words, running the call command at the Command Prompt or MS-DOS prompt will do nothing.
Cd
The cd command is the shorthand version of the chdir command. The cd command is available in all versions of Windows, as well as in MS-DOS.
Certreq
The certreq command is used to perform various certification authority (CA) certificate functions. The certreq command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Certutil
The certutil command is used to dump and display certification authority (CA) configuration information in addition to other CA functions. The certutil command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Change
The change command changes various terminal server settings like install modes, COM port mappings, and logons. The change command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Chcp
The chcp command displays or configures the active code page number. The chcp command is available in all versions of Windows, as well as in MS-DOS.
Chdir
The chdir command is used to display the drive letter and folder that you are currently in. Chdir can also be used to change the drive and/or directory that you want to work in. The chdir command is available in all versions of Windows, as well as in MS-DOS.
Checknetisolation
The checknetisolation command is used to test apps that require network capabilities. The checknetisolation command is available in Windows 11, Windows 10, and Windows 8.
Chglogon
The chglogon command enables, disables, or drains terminal server session logins. The chglogon command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. Executing the chglogon command is the same as executing change logon.
Chgport
The chgport command can be used to display or change COM port mappings for DOS compatibility. The chgport command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. Executing the chgport command is the same as executing change port.
Chgusr
The chgusr command is used to change the install mode for the terminal server. The chgusr command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. Executing the chgusr command is the same as executing change user.
Chkdsk
The chkdsk command, often referred to as check disk, is used to identify and correct certain hard drive errors. The chkdsk command is available in all versions of Windows, as well as in MS-DOS.
Chkntfs
The chkntfs command is used to configure or display the checking of the disk drive during the Windows boot process. The chkntfs command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Choice
The choice command is used within a script or batch program to provide a list of choices and return the value of that choice to the program. The choice command is available in MS-DOS and all versions of Windows except Windows XP. Use the set command with the /p switch in place of the choice command in batch files and scripts that you plan to use in Windows XP.
Cipher
The cipher command shows or changes the encryption status of files and folders on NTFS partitions. The cipher command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Clip
The clip command is used to redirect the output from any command to the clipboard in Windows. The clip command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Cls
The cls command clears the screen of all previously entered commands and other text. The cls command is available in all versions of Windows, as well as in MS-DOS.
Cmd
The cmd command starts a new instance of the cmd.exe command interpreter. The cmd command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Cmdkey
The cmdkey command is used to show, create, and remove stored user names and passwords. The cmdkey command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Cmstp
The cmstp command installs or uninstalls a Connection Manager service profile. The cmstp command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Color
The color command is used to change the colors of the text and background within the Command Prompt window. The color command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Command
The command command starts a new instance of the command.com command interpreter. The command command is available in MS-DOS as well as in all 32-bit versions of Windows. The command command is not available in 64-bit versions of Windows.
Comp
The comp command is used to compare the contents of two files or sets of files. The comp command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Compact
The compact command is used to show or change the compression state of files and directories on NTFS partitions. The compact command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Convert
The convert command is used to convert FAT or FAT32 formatted volumes to the NTFS format. The convert command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Copy
The copy command does simply that — it copies one or more files from one location to another. The copy command is available in all versions of Windows, as well as in MS-DOS. The xcopy command is considered to be a more «powerful» version of the copy command.
Cscript
The cscript command is used to execute scripts via Microsoft Script Host. The cscript command is available in all versions of Windows. The cscript command is most popularly used to manage printers from the command line using scripts like prncnfg.vbs, prndrvr.vbs, prnmngr.vbs, and others.
Ctty
The ctty command is used to change the default input and output devices for the system. The ctty command is available in Windows 98 and 95 as well as in MS-DOS. The functions provided by the ctty command were no longer necessary beginning in Windows XP because the command.com interpreter (MS-DOS) is no longer the default command line interpreter.
Date
The date command is used to show or change the current date. The date command is available in all versions of Windows, as well as in MS-DOS.
Dblspace
The dblspace command is used to create or configure DoubleSpace compressed drives. The dblspace command is available in Windows 98 and 95, as well as in MS-DOS. DriveSpace, executed using the drvspace command, is an updated version of DoubleSpace. Windows began handling compression beginning in Windows XP.
Debug
The debug command starts Debug, a command line application used to test and edit programs. The debug command is available in MS-DOS as well as in all 32-bit versions of Windows. The debug command is not available in 64-bit versions of Windows.
Defrag
The defrag command is used to defragment a drive you specify. The defrag command is the command line version of Microsoft’s Disk Defragmenter. The defrag command is available in all versions of Windows, as well as in MS-DOS.
Del
The del command is used to delete one or more files. The del command is available in all versions of Windows, as well as in MS-DOS. The del command is the same as the erase command.
Deltree
The deltree command is used to delete a directory and all the files and subdirectories within it. The deltree command is available in Windows 98 and 95, as well as in MS-DOS. Beginning in Windows XP, a folder and its files and subfolders can be removed using the /s function of the rmdir command. Deltree was no longer needed with this new rmdir ability so the command was removed.
Diantz
The diantz command is used to losslessly compress one or more files. The diantz command is sometimes called Cabinet Maker. The diantz command is available in Windows 7, Windows Vista, and Windows XP. The diantz command is the same as the makecab command.
Dir
The dir command is used to display a list of files and folders contained inside the folder that you are currently working in. The dir command also displays other important information like the hard drive’s serial number, the total number of files listed, their combined size, the total amount of free space left on the drive, and more. The dir command is available in all versions of Windows, as well as in MS-DOS.
Diskcomp
The diskcomp command is used to compare the contents of two floppy disks. The diskcomp command is available in all versions of Windows, as well as in MS-DOS, with the exclusion of Windows 11 and Windows 10.
Diskcopy
The diskcopy command is used to copy the entire contents of one floppy disk to another. The diskcopy command is available in all versions of Windows, as well as in MS-DOS, with the exclusion of Windows 11 and Windows 10.
Diskpart
The diskpart command is used to create, manage, and delete hard drive partitions. The diskpart command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The diskpart command replaced the fdisk command beginning in Windows XP.
Diskperf
The diskperf command is used to manage disk performance counters remotely. The diskperf command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Diskraid
The diskraid command starts the DiskRAID tool which is used to manage and configure RAID arrays. The diskraid command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Dism
The dism command starts the Deployment Image Servicing and Management tool (DISM). The DISM tool is used to manage features in Windows images. The dism command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Dispdiag
The dispdiag command is used to output a log of information about the display system. The dispdiag command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Djoin
The djoin command is used to create a new computer account in a domain. The djoin command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Doskey
The doskey command is used to edit command lines, create macros, and recall previously entered commands. The doskey command is available in all versions of Windows, as well as in MS-DOS.
Dosshell
The dosshell command starts DOS Shell, a graphical file management tool for MS-DOS. The dosshell command is available in Windows 95 (in MS-DOS mode) and also in MS-DOS version 6.0 and later MS-DOS versions that were upgraded from previous versions that contained the dosshell command. A graphical file manager, Windows Explorer, became an integrated part of the operating system beginning in Windows 95.
Dosx
The dosx command is used to start DOS Protected Mode Interface (DPMI), a special mode designed to give MS-DOS applications access to more than the normally allowed 640 KB. The dosx command is available in Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The dosx command is not available in 64-bit versions of Windows. The dosx command and DPMI is only available in Windows to support older MS-DOS programs.
Driverquery
The driverquery command is used to show a list of all installed drivers. The driverquery command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Drvspace
The drvspace command is used to create or configure DriveSpace compressed drives. The drvspace command is available in Windows 98 and 95, as well as in MS-DOS. DriveSpace is an updated version of DoubleSpace, executed using the dblspace command. Windows began handling compression beginning in Windows XP.
Echo
The echo command is used to show messages, most commonly from within script or batch files. The echo command can also be used to turn the echoing feature on or off. The echo command is available in all versions of Windows, as well as in MS-DOS.
Edit
The edit command starts the MS-DOS Editor tool which is used to create and modify text files. The edit command is available in MS-DOS as well as in all 32-bit versions of Windows. The edit command is not available in 64-bit versions of Windows.
Edlin
The edlin command starts the Edlin tool which is used to create and modify text files from the command line. The edlin command is available in all 32-bit versions of Windows but is not available in 64-bit versions of Windows. In MS-DOS, the edlin command is only available up to MS-DOS 5.0, so unless your later version of MS-DOS was upgraded from 5.0 or prior, you won’t see the edlin command.
Emm386
The emm386 command is used to give MS-DOS access to more than 640 KB of memory (RAM). The emm386 command is available in Windows 98 and 95, as well as in MS-DOS. Windows itself has access to extended and expanded memory beginning in Windows 95.
Endlocal
The endlocal command is used to end the localization of environment changes inside a batch or script file. The endlocal command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Erase
The erase command is used to delete one or more files. The erase command is available in all versions of Windows, as well as in MS-DOS. The erase command is the same as the del command.
Esentutl
The esentutl command is used to manage Extensible Storage Engine databases. The esentutl command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Eventcreate
The eventcreate command is used to create a custom event in an event log. The eventcreate command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Eventtriggers
The eventtriggers command is used to configure and display event triggers. The eventtriggers command is available in Windows XP. Beginning in Windows Vista, event triggers are created using the Attach Task To This Event feature in Event Viewer, making the eventtriggers command unnecessary.
Exe2bin
The exe2bin command is used to convert a file of the EXE file type (executable file) to a binary file. The exe2bin command is available in 32-bit versions of Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The exe2bin command is not available in any 64-bit version of Windows.
Exit
The exit command is used to end the cmd.exe (Windows) or command.com (MS-DOS) session that you’re currently working in. The exit command is available in all versions of Windows, as well as in MS-DOS.
Expand
The expand command is used to extract the files and folders contained in Microsoft Cabinet (CAB) files. The expand command is available in MS-DOS as well as in all versions of Windows. The expand command is not available in the 64-bit version of Windows XP.
Extrac32
The extrac32 command is used to extract the files and folders contained in Microsoft Cabinet (CAB) files. The extrac32 command is available in all versions of Windows. The extrac32 command is actually a CAB extraction program that can extract any Microsoft Cabinet file. Use the expand command instead of the extrac32 command if possible.
Extract
The extract command is used to extract the files and folders contained in Microsoft Cabinet (CAB) files. The extract command is available in Windows 98 and 95. The extract command was replaced by the expand command beginning in Windows XP.
Fasthelp
The fasthelp command provides more detailed information on any of the other MS-DOS commands. The fasthelp command is only available in MS-DOS. The help command replaced the fasthelp command beginning in Windows 95.
Fastopen
The fastopen command is used to add a program’s hard drive location to a special list stored in memory, potentially improving the program’s launch time by removing the need for MS-DOS to locate the application on the drive. The fastopen command is available in MS-DOS as well as in all 32-bit versions of Windows. The fastopen command is not available in 64-bit versions of Windows. Fastopen is only available in Windows 10, Windows 8, 7, Vista, and XP to support older MS-DOS files.
Fc
The fc command is used to compare two individual or sets of files and then show the differences between them. The fc command is available in all versions of Windows, as well as in MS-DOS.
Fdisk
The fdisk command is used to create, manage, and delete hard drive partitions. The fdisk command is available in Windows 98 and 95, as well as in MS-DOS. The fdisk command was replaced by the diskpart command beginning in Windows XP. Partition management is also available from Disk Management in Windows 11, 10, 8, 7, Vista, and XP.
Find
The find command is used to search for a specified text string in one or more files. The find command is available in all versions of Windows, as well as in MS-DOS.
Findstr
The findstr command is used to find text string patterns in one or more files. The findstr command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Finger
The finger command is used to return information about one or more users on a remote computer that’s running the Finger service. The finger command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Fltmc
The fltmc command is used to load, unload, list, and otherwise manage Filter drivers. The fltmc command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Fondue
The fondue command, short for Features on Demand User Experience Tool, is used to install any of the several optional Windows features from the command line. The fondue command is available in Windows 11, Windows 10, and Windows 8. Optional Windows features can also be installed from the Programs and Features applet in Control Panel.
For
The for command is used to run a specified command for each file in a set of files. The for command is most often used within a batch or script file. The for command is available in all versions of Windows, as well as in MS-DOS.
Forcedos
The forcedos command is used to start the specified program in the MS-DOS subsystem. The forcedos command is only available in 32-bit versions of Windows XP. The forcedos command is only used for MS-DOS programs that are not recognized as such by Windows XP.
Forfiles
The forfiles command selects one or more files to execute a specified command on. The forfiles command is most often used within a batch or script file. The forfiles command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Format
The format command is used to format a drive in the file system that you specify. The format command is available in all versions of Windows, as well as in MS-DOS. Drive formatting is also available from Disk Management in Windows 11, 10, 8, 7, Vista, and XP.
Fsutil
The fsutil command is used to perform various FAT and NTFS file system tasks like managing reparse points and sparse files, dismounting a volume, and extending a volume. The fsutil command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Ftp
The ftp command can be used to transfer files to and from another computer. The remote computer must be operating as an FTP server. The ftp command is available in all versions of Windows.
Ftype
The ftype command is used to define a default program to open a specified file type. The ftype command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Getmac
The getmac command is used to display the media access control (MAC) address of all the network controllers on a system. The getmac command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Goto
The goto command is used in a batch or script file to direct the command process to a labeled line in the script. The goto command is available in all versions of Windows, as well as in MS-DOS.
Gpresult
The gpresult command is used to display Group Policy settings. The gpresult command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Gpupdate
The gpupdate command is used to update Group Policy settings. The gpupdate command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Graftabl
The graftabl command is used to enable the ability of Windows to display an extended character set in graphics mode. The graftabl command is available in all versions of Windows and in MS-DOS up to version 5.0. The graftabl command is not available in 64-bit versions of Windows.
Graphics
The graphics command is used to load a program that can print graphics. The graphics command is available in MS-DOS as well as in all 32-bit versions of Windows. The graphics command is not available in 64-bit versions of Windows.
Help
The help command provides more detailed information on any of the other Command Prompt or MS-DOS commands. The help command is available in all versions of Windows, as well as in MS-DOS.
Hostname
The hostname command displays the name of the current host. The hostname command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Hwrcomp
The hwrcomp command is used to compile custom dictionaries for handwriting recognition. The hwrcomp command is available in Windows 8 and Windows 7.
Hwrreg
The hwrreg command is used to install a previously compiled custom dictionary for handwriting recognition. The hwrreg command is available in Windows 8 and Windows 7.
Icacls
The icacls command is used to display or change access control lists of files. The icacls command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. The icacls command is an updated version of the cacls command.
If
The if command is used to perform conditional functions in a batch file. The if command is available in all versions of Windows, as well as in MS-DOS.
Interlnk
The interlnk command is used to connect two computers via a serial or parallel connection to share files and printers. The interlnk command is only available in MS-DOS. The ability to directly connect two computers is handled by the networking functions in all versions of Windows.
Intersvr
The intersvr command is used to start the Interlnk server and to copy Interlnk files from one computer to another. The intersvr command is only available in MS-DOS. The ability to directly connect two computers is handled by the networking functions in all versions of Windows.
Ipconfig
The ipconfig command is used to display detailed IP information for each network adapter utilizing TCP/IP. The ipconfig command can also be used to release and renew IP addresses on systems configured to receive them via a DHCP server. The ipconfig command is available in all versions of Windows.
Ipxroute
The ipxroute command is used to display and change information about IPX routing tables. The ipxroute command is available in Windows XP. Microsoft removed their built-in NetWare client beginning in Windows Vista, removing the associated ipxroute command as well.
Irftp
The irftp command is used to transmit files over an infrared link. The irftp command is available in Windows 8, Windows 7, and Windows Vista.
Iscsicli
The iscsicli command starts the Microsoft iSCSI Initiator, used to manage iSCSI. The iscsicli command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Kb16
The kb16 command is used to support MS-DOS files that need to configure a keyboard for a specific language. The kb16 command is available in Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The kb16 command is not available in 64-bit versions of Windows. The kb16 command replaced the keyb command beginning in Windows XP but only exists to support older MS-DOS files.
Keyb
The keyb command is used to configure a keyboard for a specific language. The keyb command is available in Windows 98 and 95, as well as in MS-DOS. See the kb16 command for an equivalent command in later versions of Windows. Keyboard language settings are handled by the Region and Language or Regional and Language Options (depending on the version of Windows) Control Panel applets in Windows beginning in Windows XP.
Klist
The klist command is used to list Kerberos service tickets. The klist command can also be used to purge Kerberos tickets. The klist command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Ksetup
The ksetup command is used to configure connections to a Kerberos server. The ksetup command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Ktmutil
The ktmutil command starts the Kernel Transaction Manager utility. The ktmutil command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Label
The label command is used to manage the volume label of a disk. The label command is available in all versions of Windows, as well as in MS-DOS.
Lh
The lh command is the shorthand version of the loadhigh command. The lh command is available in Windows 98 and 95, as well as in MS-DOS.
Licensingdiag
The licensingdiag command is a tool used to generate a text-based log and other data files that contain product activation and other Windows licensing information. The licensingdiag command is available in Windows 11, Windows 10, and Windows 8.
Loadfix
The loadfix command is used to load the specified program in the first 64K of memory and then runs the program. The loadfix command is available in MS-DOS as well as in all 32-bit versions of Windows. The loadfix command is not available in 64-bit versions of Windows.
Loadhigh
The loadhigh command is used to load a program into high memory and is usually used from within the autoexec.bat file. The loadhigh command is available in Windows 98 and 95, as well as in MS-DOS. Memory usage is handled automatically beginning in Windows XP.
Lock
The lock command is used to lock a drive, enabling direct disk access for a program. The lock command is only available in Windows 98 and 95. Drive locking is no longer available as of Windows XP.
Lodctr
The lodctr command is used to update registry values related to performance counters. The lodctr command is available in all versions of Windows.
Logman
The logman command is used to create and manage Event Trace Session and Performance logs. The logman command also supports many functions of Performance Monitor. The logman command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Logoff
The logoff command is used to terminate a session. The logoff command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Lpq
The lpq command displays the status of a print queue on a computer running Line Printer Daemon (LPD). The lpq command is available in all versions of Windows. The lpq command is not available by default in Windows 11, 10, 8, 7, or Vista, but can be enabled by turning on the LPD Print Service and LPR Port Monitor features from Programs and Features in Control Panel.
Lpr
The lpr command is used to send a file to a computer running Line Printer Daemon (LPD). The lpr command is available in all versions of Windows. The lpr command is not available by default in Windows 11, 10, 8, 7, or Vista, but can be enabled by turning on the LPD Print Service and LPR Port Monitor features from Programs and Features in Control Panel.
Makecab
The makecab command is used to losslessly compress one or more files. The makecab command is sometimes called Cabinet Maker. The makecab command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The makecab command is the same as the diantz command, a command that was removed after Windows 7.
Manage-bde
The manage-bde command is used to configure BitLocker Drive Encryption from the command line. The manage-bde command is available in Windows 11, Windows 10, Windows 8, and Windows 7. A script by the name of manage-bde.wsf exists in Windows Vista and can be used with the cscript command to perform BitLocker tasks from the command line in that operating system.
Md
The md command is the shorthand version of the mkdir command. The md command is available in all versions of Windows, as well as in MS-DOS.
Mem
The mem command shows information about used and free memory areas and programs that are currently loaded into memory in the MS-DOS subsystem. The mem command is available in MS-DOS as well as in all 32-bit versions of Windows. The mem command is not available in 64-bit versions of Windows.
Memmaker
The memmaker command is used to start MemMaker, a memory optimization tool. The memaker command is available in Windows 98 and 95, as well as in MS-DOS. Memory usage is automatically optimized beginning in Windows XP.
Mkdir
The mkdir command is used to create a new folder. The mkdir command is available in all versions of Windows, as well as in MS-DOS.
Mklink
The mklink command is used to create a symbolic link. The mklink command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Mode
The mode command is used to configure system devices, most often COM and LPT ports. The mode command is available in all versions of Windows, as well as in MS-DOS.
Mofcomp
The mofcomp command properly displays the data within a Managed Object Format (MOF) file. The mofcomp command is available in all versions of Windows.
More
The more command is used to display the information contained in a text file. The more command can also be used to paginate the results of any other Command Prompt or MS-DOS command. The more command is available in all versions of Windows, as well as in MS-DOS.
Mount
The mount command is used to mount Network File System (NFS) network shares. The mount command is available in Windows 7 and Windows Vista. The mount command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Services for NFS Windows feature from Programs and Features in Control Panel. The mount command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Mountvol
The mountvol command is used to display, create, or remove volume mount points. The mountvol command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Move
The move command is used to move one or more files from one folder to another. The move command is also used to rename directories. The move command is available in all versions of Windows, as well as in MS-DOS.
Mrinfo
The mrinfo command is used to provide information about a router’s interfaces and neighbors. The mrinfo command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Msav
The msav command starts Microsoft Antivirus. The msav command is only available in MS-DOS. Microsoft Antivirus was designed for MS-DOS and Windows 3.x only. Microsoft provides an optional virus protection suite called Microsoft Security Essentials for Windows XP and later operating systems, and third-party antivirus tools are available for all versions of Windows.
Msbackup
The msbackup command starts Microsoft Backup, a tool used to back up and restore one or more files. The msbackup command is only available in MS-DOS. The msbackup command was replaced with Microsoft Backup beginning in Windows 95 and then Backup and Restore in later versions of Windows.
Mscdex
The mscdex command is used to provide CD-ROM access to MS-DOS. The mscdex command is available in Windows 98 and 95, as well as in MS-DOS. Windows provides access to CD-ROM drives for the MS-DOS subsystem beginning in Windows XP, so the mscdex command is unnecessary in this and later operating systems.
Msd
The msd command starts Microsoft Diagnostics, a system information tool. The msd command is only available in MS-DOS. The msd command was replaced with System Information beginning in Windows 95.
Msg
The msg command is used to send a message to a user. The msg command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Msiexec
The msiexec command is used to start Windows Installer, a tool used to install and configure software. The msiexec command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Muiunattend
The muiunattend command starts the Multilanguage User Interface unattended setup process. The muiunattend command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Nbtstat
The nbtstat command is used to show TCP/IP information and other statistical information about a remote computer. The nbtstat command is available in all versions of Windows.
Net
The net command is used to display, configure, and correct a wide variety of network settings. The net command is available in all versions of Windows.
Net1
The net1 command is used to display, configure, and correct a wide variety of network settings. The net1 command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The net command should be used instead of the net1 command. The net1 command was made available in Windows NT and Windows 2000 as a temporary fix for a Y2K issue that the net command had, which was corrected before the release of Windows XP. The net1 command remains in later versions of Windows only for compatibility with older programs and scripts that utilized the command.
Netcfg
The netcfg command is used to install the Windows Preinstallation Environment (WinPE), a lightweight version of Windows used to deploy workstations. The netcfg command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Netsh
The netsh command is used to start Network Shell, a command-line utility used to manage the network configuration of the local, or a remote, computer. The netsh command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Netstat
The netstat command is most commonly used to display all open network connections and listening ports. The netstat command is available in all versions of Windows.
Nfsadmin
The nfsadmin command is used to manage Server for NFS or Client for NFS from the command line. The nfsadmin command is available in Windows 7 and Windows Vista. The nfsadmin command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Services for NFS Windows feature from Programs and Features in Control Panel. The nfsadmin command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Nlsfunc
The nlsfunc command is used to load information specific to a particular country or region. The nlsfunc command is available in MS-DOS as well as in all 32-bit versions of Windows. The nlsfunc command is not available in 64-bit versions of Windows. Nlsfunc is only available in Windows 10, 8, 7, Vista, and XP to support older MS-DOS files.
Nltest
The nltest command is used to test secure channels between Windows computers in a domain and between domain controllers that are trusting other domains. The nltest command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Nslookup
The nslookup is most commonly used to display the hostname of an entered IP address. The nslookup command queries your configured DNS server to discover the IP address. The nslookup command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Ntbackup
The ntbackup command is used to perform various backup functions from the Command Prompt or from within a batch or script file. The ntbackup command is available in Windows XP. The ntbackup command was replaced with the wbadmin beginning in Windows Vista.
Ntsd
The ntsd command is used to perform certain command line debugging tasks. The ntsd command is available in Windows XP. The ntsd command was removed beginning in Windows Vista due to the addition of dump file support in Task Manager.
Ocsetup
The ocsetup command starts the Windows Optional Component Setup tool, used to install additional Windows features. The ocsetup command is available in Windows 8, Windows 7, and Windows Vista. Beginning in Windows 8, Microsoft is depreciating the ocsetup command in favor of the dism command.
Openfiles
The openfiles command is used to display and disconnect open files and folders on a system. The openfiles command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Path
The path command is used to display or set a specific path available to executable files. The path command is available in all versions of Windows, as well as in MS-DOS.
Pathping
The pathping command functions much like the tracert command but will also report information about network latency and loss at each hop. The pathping command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Pause
The pause command is used within a batch or script file to pause the processing of the file. When the pause command is used, a «Press any key to continue…» message displays in the command window. The pause command is available in all versions of Windows, as well as in MS-DOS.
Pentnt
The pentnt command is used to detect floating point division errors in the Intel Pentium chip. The pentnt command is also used to enable floating point emulation and disable floating point hardware. The pentnt command is available in Windows XP. The pentnt command was removed beginning in Windows Vista due to the lack of Intel Pentium CPU use at the time of this operating system release.
Ping
The ping command sends an Internet Control Message Protocol (ICMP) Echo Request message to a specified remote computer to verify IP-level connectivity. The ping command is available in all versions of Windows.
Pkgmgr
The pkgmgr command is used to start the Windows Package Manager from the Command Prompt. Package Manager installs, uninstalls, configures, and updates features and packages for Windows. The pkgmgr command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Pnpunattend
The pnpunattend command is used to automate the installation of hardware device drivers. The pnpunattend command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Pnputil
The pnputil command is used to start the Microsoft PnP Utility, a tool used to install a Plug and Play device from the command line. The pnputil command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Popd
The popd command is used to change the current directory to the one most recently stored by the pushd command. The popd command is most often utilized from within a batch or script file. The popd command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Power
The power command is used to reduce the power consumed by a computer by monitoring software and hardware devices. The power command is available in Windows 98 and 95, as well as in MS-DOS. The power command was replaced by operating system integrated power management functions beginning in Windows XP.
Powercfg
The powercfg command is used to manage the Windows power management settings from the command line. The powercfg command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Print
The print command is used to print a specified text file to a specified printing device. The print command is available in all versions of Windows, as well as in MS-DOS.
Prompt
The prompt command is used to customize the appearance of the prompt text in Command Prompt or MS-DOS. The prompt command is available in all versions of Windows, as well as in MS-DOS.
Pushd
The pushd command is used to store a directory for use, most commonly from within a batch or script program. The pushd command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Pwlauncher
The pwlauncher command is used to enable, disable, or show the status of your Windows To Go startup options. The pwlauncher command is available in Windows 11, 10, and 8.
Qappsrv
The qappsrv command is used to display all Remote Desktop Session Host servers available on the network. The qappsrv command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Qbasic
The qbasic command starts QBasic, the MS-DOS based programming environment for the BASIC programming language. The qbasic command is available in Windows 98 and 95, as well as in MS-DOS. The qbasic command is not installed by default with Windows 98 or 95 but is available from the installation disc or disks.
Qprocess
The qprocess command is used to display information about running processes. The qprocess command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Query
The query command is used to display the status of a specified service. The query command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Quser
The quser command is used to display information about users currently logged on to the system. The quser command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Qwinsta
The qwinsta command is used to display information about open Remote Desktop Sessions. The qwinsta command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Rasautou
The rasautou command is used to manage Remote Access Dialer AutoDial addresses. The rasautou command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Rasdial
The rasdial command is used to start or end a network connection for a Microsoft client. The rasdial command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Rcp
The rcp command is used to copy files between a Windows computer and a system running the rshd daemon. The rcp command is available in Windows 7, Windows Vista, and Windows XP. The rcp command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Subsystem for UNIX-based Applications Windows feature from Programs and Features in Control Panel and then installing the Utilities and SDK for UNIX-based Applications available here for Windows Vista and here for Windows 7. The rcp command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Rd
The rd command is the shorthand version of the rmdir command. The rd command is available in all versions of Windows, as well as in MS-DOS.
Rdpsign
The rdpsign command is used to sign a Remote Desktop Protocol (RDP) file. The rdpsign command is available in Windows 7.
Reagentc
The reagentc command is used to configure the Windows Recovery Environment (RE). The reagentc command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Recimg
The recimg command is used to create a custom refresh image. The recimg command is available in Windows 8.
Recover
The recover command is used to recover readable data from a bad or defective disk. The recover command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Reg
The reg command is used to manage the Windows Registry from the command line. The reg command can perform common registry functions like adding registry keys, exporting the registry, etc. The reg command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Regini
The regini command is used to set or change registry permissions and registry values from the command line. The regini command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Register-cimprovider
The register-cimprovider command is used to register a Common Information Model (CIM) Provider in Windows. The register-cimprovider command is available in Windows 11, Windows 10, and Windows 8.
Regsvr32
The regsvr32 command is used to register a DLL file as a command component in the Windows Registry. The regsvr32 command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Relog
The relog command is used to create new performance logs from data in existing performance logs. The relog command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Rem
The rem command is used to record comments or remarks in a batch or script file. The rem command is available in all versions of Windows, as well as in MS-DOS.
Ren
The ren command is the shorthand version of the rename command. The ren command is available in all versions of Windows, as well as in MS-DOS.
Rename
The rename command is used to change the name of the individual file that you specify. The rename command is available in all versions of Windows, as well as in MS-DOS.
Repair-bde
The repair-bde command is used to repair or decrypt a damaged drive that’s been encrypted using BitLocker. The repair-bde command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Replace
The replace command is used to replace one or more files with one or more other files. The replace command is available in all versions of Windows, as well as in MS-DOS.
Reset
The reset command, executed as reset session, is used to reset the session subsystem software and hardware to known initial values. The reset command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Restore
The restore command is used to restore files that were backed up using the backup command. The restore command is only available in MS-DOS. The backup command was only available up to MS-DOS 5.00 but the restore command was included by default with later versions of MS-DOS to provide a way to restore files that were backed up in previous versions of MS-DOS.
Rexec
The rexec command is used to run commands on remote computers running the rexec daemon. The rexec command is available in Windows Vista and Windows XP. The rsh command is not available by default in Windows Vista but can be enabled by turning on the Subsystem for UNIX-based Applications Windows feature from Programs and Features in Control Panel and then installing the Utilities and SDK for UNIX-based Applications available here. The rexec command is not available in Windows 7 but can be executed in Windows XP via Windows XP Mode if need be.
Rmdir
The rmdir command is used to delete an existing or completely empty folder. The rmdir command is available in all versions of Windows, as well as in MS-DOS.
Robocopy
The robocopy command is used to copy files and directories from one location to another. This command is also called Robust File Copy. The robocopy command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. The robocopy command is superior to both the copy command and the xcopy command because robocopy supports many more options.
Route
The route command is used to manipulate network routing tables. The route command is available in all versions of Windows.
Rpcinfo
The rpcinfo command makes a remote procedure call (RPC) to an RPC server and reports what it finds. The rpcinfo command is available in Windows 7 and Windows Vista. The rpcinfo command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Services for NFS Windows feature from Programs and Features in Control Panel. The rpcinfo command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Rpcping
The rpcping command is used to ping a server using RPC. The rpcping command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Rsh
The rsh command is used to run commands on remote computers running the rsh daemon. The rsh command is available in Windows 7, Windows Vista, and Windows XP. The rsh command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Subsystem for UNIX-based Applications Windows feature from Programs and Features in Control Panel and then installing the Utilities and SDK for UNIX-based Applications available here for Windows Vista and here for Windows 7. The rsh command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Rsm
The rsm command is used to manage media resources using Removable Storage. The rsm command is available in Windows Vista and Windows XP. The rsm command was optional in Windows Vista and then removed in Windows 7 due to Removable Storage Manager being removed from the operating system. Search for the rsm command in the C:\Windows\winsxs folder in Windows Vista if you’re having trouble executing the command.
Runas
The runas command is used to execute a program using another user’s credentials. The runas command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Rwinsta
The rwinsta command is the shorthand version of the reset session command. The rwinsta command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Sc
The sc command is used to configure information about services. The sc command communicates with the Service Control Manager. The sc command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Scandisk
The scandisk command is used to start Microsoft ScanDisk, a disk repair program. The scandisk command is available in Windows 98 and 95, as well as in MS-DOS. The scandisk command was replaced by the chkdsk command beginning in Windows XP.
Scanreg
The scanreg command starts Windows Registry Checker, a basic registry repair program and backup utility. The scanreg command is available in Windows 98 and Windows 95. The functions provided by the scanreg command were no longer necessary beginning in Windows XP due to changes in how the Windows Registry functions.
Schtasks
The schtasks command is used to schedule specified programs or commands to run at certain times. The schtasks command can be used to create, delete, query, change, run, and end scheduled tasks. The schtasks command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Sdbinst
The sdbinst command is used to deploy customized SDB database files. The sdbinst command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Secedit
The secedit command is used to configure and analyze system security by comparing the current security configuration to a template. The secedit command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Set
The set command is used to display, enable, or disable environment variables in MS-DOS or from the Command Prompt. The set command is available in all versions of Windows, as well as in MS-DOS.
Setlocal
The setlocal command is used to start the localization of environment changes inside a batch or script file. The setlocal command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Setspn
The setspn command is used to manage the Service Principal Names (SPN) for an Active Directory (AD) service account. The setspn command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Setver
The setver command is used to set the MS-DOS version number that MS-DOS reports to a program. The setver command is available in MS-DOS as well as in all 32-bit versions of Windows. The setver command is not available in 64-bit versions of Windows.
Setx
The setx command is used to create or change environment variables in the user environment or the system environment. The setx command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Sfc
The sfc command is used to verify and replace important Windows system files. The sfc command is also referred to as System File Checker or Windows Resource Checker, depending on the operating system. The sfc command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Shadow
The shadow command is used to monitor another Remote Desktop Services session. The shadow command is available in Windows 7, Windows Vista, and Windows XP.
Share
The share command is used to install file locking and file sharing functions in MS-DOS. The share command is available in MS-DOS as well as in all 32-bit versions of Windows. The share command is not available in 64-bit versions of Windows. Share is only available in Windows 10, 8, 7, Vista, and XP to support older MS-DOS files.
Shift
The shift command is used to change the position of replaceable parameters in a batch or script file. The shift command is available in all versions of Windows, as well as in MS-DOS.
Showmount
The showmount command is used to display information about NFS-mounted file systems. The showmount command is available in Windows 7 and Windows Vista. The showmount command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Services for NFS Windows feature from Programs and Features in Control Panel. The showmount command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Shutdown
The shutdown command can be used to shut down, restart, or log off the current system or a remote computer. The shutdown command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Smartdrv
The smartdrv command installs and configures SMARTDrive, a disk caching utility for MS-DOS. The smartdrv command is available in Windows 98 and 95, as well as in MS-DOS. Caching is automatic beginning in Windows XP, making the smartdrv command unnecessary.
Sort
The sort command is used to read data from a specified input, sort that data, and return the results of that sort to the Command Prompt screen, a file, or another output device. The sort command is available in all versions of Windows, as well as in MS-DOS.
Start
The start command is used to open a new command line window to run a specified program or command. The start command can also be used to start an application without creating a new window. The start command is available in all versions of Windows.
Subst
The subst command is used to associate a local path with a drive letter. The subst command is a lot like the net use command except a local path is used instead of a shared network path. The subst command is available in all versions of Windows, as well as in MS-DOS. The subst command replaced the assign command beginning with MS-DOS 6.0.
Sxstrace
The sxstrace command is used to start the WinSxs Tracing Utility, a programming diagnostic tool. The sxstrace command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Sys
The sys command is used to copy the MS-DOS system files and command interpreter to a disk. The sys command is available in Windows 98 and 95, as well as in MS-DOS. The sys command is used most often to create a simple bootable disk or hard drive. The necessary system files for Windows are too large to fit on a disk, so the sys command was removed beginning in Windows XP.
Systeminfo
The systeminfo command is used to display basic Windows configuration information for the local or a remote computer. The systeminfo command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Takeown
The takedown command is used to regain access to a file that that an administrator was denied access to when reassigning ownership of the file. The takeown command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Taskkill
The taskkill command is used to terminate a running task. The taskkill command is the command line equivalent of ending a process in Task Manager in Windows. The taskkill command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tasklist
Displays a list of applications, services, and the Process ID (PID) currently running on either a local or a remote computer. The tasklist command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tcmsetup
The tcmsetup command is used to set up or disable the Telephony Application Programming Interface (TAPI) client. The tcmsetup command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Telnet
The telnet command is used to communicate with remote computers that use the Telnet protocol. The telnet command is available in all versions of Windows. The telnet command is not available by default in Windows 11, 10, 8, 7, or Vista, but can be enabled by turning on the Telnet Client Windows feature from Programs and Features in Control Panel.
Tftp
The tftp command is used to transfer files to and from a remote computer that’s running the Trivial File Transfer Protocol (TFTP) service or daemon. The tftp command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The tftp command is not available by default in some versions of Windows, but can be enabled by turning on the TFTP Client Windows feature from Programs and Features in Control Panel.
Time
The time command is used to show or change the current time. The time command is available in all versions of Windows, as well as in MS-DOS.
Timeout
The timeout command is typically used in a batch or script file to provide a specified timeout value during a procedure. The timeout command can also be used to ignore keypresses. The timeout command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Title
The title command is used to set the Command Prompt window title. The title command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tlntadmn
The tlntadmn command is used to administer a local or remote computer running Telnet Server. The tlntadmn command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP. The tlntadmn command is not available by default in some versions of Windows but can be enabled by turning on the Telnet Server Windows feature from Programs and Features in Control Panel.
Tpmvscmgr
The tpmvscmgr command is used to create and destroy TPM virtual smart cards. The tpmvscmgr command is available in Windows 11, Windows 10, and Windows 8.
Tracerpt
The tracerpt command is used to process event trace logs or real-time data from instrumented event trace providers. The tracerpt command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tracert
The tracert command sends Internet Control Message Protocol (ICMP) Echo Request messages to a specified remote computer with increasing Time to Live (TTL) field values and displays the IP address and hostname, if available, of the router interfaces between the source and destination. The tracert command is available in all versions of Windows.
Tree
The tree command is used to graphically display the folder structure of a specified drive or path. The tree command is available in all versions of Windows, as well as in MS-DOS.
Tscon
The tscon command is used to attach a user session to a Remote Desktop session. The tscon command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tsdiscon
The tsdiscon command is used to disconnect a Remote Desktop session. The tsdiscon command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tskill
The tskill command is used to end the specified process. The tskill command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tsshutdn
The tsshutdn command is used to remotely shut down or restart a terminal server. The tsshutdn command is available in Windows XP. The ability to shut down a computer remotely is also available in the more powerful shutdown command, so tsshutdn was removed beginning in Windows Vista.
Type
The type command is used to display the information contained in a text file. The type command is available in all versions of Windows, as well as in MS-DOS.
Typeperf
The typerperf command displays performance data in the Command Prompt window or writes the data to specified log file. The typeperf command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Tzutil
The tzutil command is used to display or configure the current system’s time zone. The tzutil command can also be used to enable or disable Daylight Saving Time adjustments. The tzutil command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Umount
The umount command is used to remove Network File System (NFS) mounted network shares. The umount command is available in Windows 7 and Windows Vista. The umount command is not available by default in Windows Vista or Windows 7 but can be enabled by turning on the Services for NFS Windows feature from Programs and Features in Control Panel. The umount command is not available in Windows 11, 10, or 8 because Service for UNIX (SFU) was discontinued.
Undelete
The undelete command is used to undo a deletion performed with the MS-DOS delete command. The undelete command is only available in MS-DOS. The undelete command was removed beginning in Windows 95 due to the availability of the Recycle Bin in Windows. Additionally, free file recovery programs are available from third-party software makers.
Unformat
The unformat command is used to undo the formatting on a drive performed by the MS-DOS format command. The unformat command is only available in MS-DOS. The unformat command was removed beginning in Windows 95 due to file system changes.
Unlock
The unlock command is used to unlock a drive, disabling direct disk access for a program. The unlock command is only available in Windows 98 and 95. Drive locking is no longer available as of Windows XP.
Unlodctr
The unlodctr command removes Explain text and Performance counter names for a service or device driver from the Windows Registry. The unlodctr command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Vaultcmd
The vaultcmd command is used to create, remove, and show stored credentials. The vaultcmd command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Ver
The ver command is used to display the current Windows or MS-DOS version number. The ver command is available in all versions of Windows, as well as in MS-DOS.
Verify
The verify command is used to enable or disable the ability of Command Prompt, or MS-DOS, to verify that files are written correctly to a disk. The verify command is available in all versions of Windows, as well as in MS-DOS.
Vol
The vol command shows the volume label and serial number of a specified disk, assuming this information exists. The vol command is available in all versions of Windows, as well as in MS-DOS.
Vsafe
The vsafe command is used to start VSafe, a basic virus protection system for MS-DOS. The vsafe command is only available in MS-DOS. VSafe was designed for MS-DOS and Windows 3.x only. Microsoft provides an optional virus protection suite called Microsoft Security Essentials for Windows XP and later operating systems, and third-party antivirus tools are available for all versions of Windows.
Vssadmin
The vssadmin command starts the Volume Shadow Copy Service administrative command line tool which displays current volume shadow copy backups and all installed shadow copy writers and providers. The vssadmin command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
W32tm
The w32tm command is used to diagnose issues with Windows Time. The w32tm command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Waitfor
The waitfor command is used to send or wait for a signal on a system. The waitfor command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Wbadmin
The wbadmin command is used to start and stop backup jobs, display details about a previous backup, list the items within a backup, and report on the status of a currently running backup. The wbadmin command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista. The wbadmin command replaced the ntbackup command beginning in Windows Vista.
Wecutil
The wecutil command is used to manage subscriptions to events that are forwarded from WS-Management supported computers. The wecutil command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Wevtutil
The wevtutil command starts the Windows Events Command Line Utility which is used to manage event logs and publishers. The wevtutil command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Where
The where command is used to search for files that match a specified pattern. The where command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Whoami
The whoami command is used to retrieve user name and group information on a network. The whoami command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Winmgmt
The winmgmt command starts the command line version of WMI, a scripting tool in Windows. The winmgmt command is available in all versions of Windows.
Winrm
The winrm command is used to start the command line version of Windows Remote Management, used to manage secure communications with local and remote computers using web services. The winrm command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Winrs
The winrs command is used to open a secure command window with a remote host. The winrs command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Winsat
The winsat command starts the Windows System Assessment Tool, a program that assesses various features, attributes, and capabilities of a computer running Windows. The winsat command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Wmic
The wmic command starts the Windows Management Instrumentation Command line (WMIC), a scripting interface that simplifies the use of Windows Management Instrumentation (WMI) and systems managed via WMI. The wmic command is available in Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.
Wsmanhttpconfig
The wsmanhttpconfig command is used to manage aspects of the Windows Remote Management (WinRM) service. The wsmanhttpconfig command is available in Windows 11, Windows 10, Windows 8, Windows 7, and Windows Vista.
Xcopy
The xcopy command can copy one or more files or directory trees from one location to another. The xcopy command is generally considered a more «powerful» version of the copy command through the robocopy command trumps even xcopy. The xcopy command is available in all versions of Windows, as well as in MS-DOS. A command by the name of xcopy32 existed in Windows 95 and Windows 98. To avoid a long and confusing explanation here, just know that no matter if you executed the xcopy command or the xcopy32 command, you were always executing the most updated version of the command.
Xwizard
The xwizard command, short for Extensible Wizard, is used to register data in Windows, often from a preconfigured XML file. The xwizard command is available in Windows 11, Windows 10, Windows 8, and Windows 7.
Командная строка Windows (CMD) — мощный инструмент, который предоставляет доступ к широкому набору команд для выполнения различных задач, от работы с файлами до настройки сети и автоматизации процессов. В статье рассмотрим 100 популярных команд CMD, которые пригодятся как новичкам, так и опытным пользователям. Для удобства они разделены по категориям.
Разделы
- Общие команды CMD
- Сетевые команды CMD
- Команды для управления процессами
- Команды для управления файловой системой
- Команды для управления пользователями
- Команды для управления безопасностью
- Команды для диагностики и устранения неполадок
- Команды для скриптинга и автоматизации
- Команды для управления сетевыми подключениями
- Команды для управления печатью
- Дополнительные команды в Windows
Общие команды командной строки (CMD) позволяют пользователям управлять ОС Windows через интерфейс командной строки. Они нацелены на различные задачи – от получения справочной информации до управления процессами.
- hel — выводит список всех доступных команд и их краткое описание, что полезно для получения информации о базовых командах.
- cls — очищает экран командной строки. Если в окне CMD много текста, этой командой можно убрать весь вывод и начать работу «с чистого листа».
- exit — завершает текущую сессию командной строки и закрывает окно CMD.
- echo — выводит сообщения в консоль или включает/выключает отображение команд в пакетных файлах – echo Hello, World! выведет Hello, World! на экран.
- ver — отображает версию операционной системы Windows.
- title — изменяет заголовок окна командной строки. Например, title Моя Командная Строка изменит заголовок на «Моя Командная Строка».
- pause — временно приостанавливает выполнение скрипта, но при нажатии любой клавиши можно продолжить работу.
- date — позволяет узнать или изменить текущую дату в системе.
- time — отображает или изменяет текущее время в системе.
- tasklist — выводит список всех запущенных процессов с их PID (идентификатором процесса).
- powercfg — управляет настройками энергопотребления и профилями питания.
- fc — сравнивает два файла и отображает их различия.
Сетевые команды CMD
В разделе собраны основные сетевые команды CMD, которые помогут управлять подключениями, диагностировать сетевые проблемы и выполнять разнообразные операции с сетью. Они незаменимы для системных администраторов и пользователей, нуждающихся в решении сетевых задач.
- ping — проверяет связь с удаленным узлом, отправляя ему пакеты данных. Например, ping google.com проверит доступность сервера Google.
- ipconfig — отображает конфигурацию сетевых интерфейсов системы (IP-адреса, маску подсети и шлюзы).
- netstat — выводит информацию о сетевых соединениях и открытых портах
- netstat -an — показывает все активные соединения.
- tracert — отслеживает маршрут пакета до целевого узла – tracert yandex.ru покажет все узлы, через которые проходит запрос.
- nslookup — используется для проверки информации о DNS-серверах.
- nslookup example.com — отображает IP-адрес сайта example.com.
- arp — выводит или изменяет записи ARP (Address Resolution Protocol) –: arp -a покажет текущие записи ARP.
- route — управляет таблицей маршрутизации сети – route print выведет все существующие маршруты в системе.
- net use — подключает сетевые диски. Например, net use Z: \\server\folder подключит сетевой ресурс как диск Z:.
- netsh — позволяет настраивать различные параметры сети через командную строку.
- netsh wlan show profiles — отображает сохраненные профили Wi-Fi.
Команды для управления процессами
Команды ниже позволяют эффективно управлять процессами и службами на вашем ПК: помогают запускать службы, планировать задачи, управлять активными процессами, а также выключать или перезагружать систему. С их помощью можно автоматизировать выполнение задач, получать информацию о состоянии системы и контролировать её работоспособность.
- sc — управляет службами Windows. Пример: sc start servicename запустит службу с именем servicename.
- schtasks — управляет планировщиком задач. Так, schtasks /create /tn «Моя Задача» /tr notepad.exe /sc once /st 12:00 создаст задачу для запуска.
- start — запускает программу или команду в новом окне. Например, start notepad откроет блокнот.
- wmic — взаимодействует с системой через Windows Management Instrumentation – wmic process list brief покажет список процессов.
- shutdown — выключает, перезагружает или завершает работу системы. Так, shutdown /s /f /t 0 немедленно выключит компьютер.
- systeminfo — выводит информацию о системе, включая версию Windows, параметры оборудования и установленные обновления.
Команды для управления файловой системой
Команды для управления файловой системой в CMD позволяют работать с файлами и папками: просматривать содержимое директорий, перемещаться между папками, создавать и удалять файлы и каталоги, копировать данные с использованием различных опций.
- dir — отображает список файлов и каталогов в указанной директории. Пример: dir C:\Windows выведет содержимое папки Windows.
- cd — меняет текущий каталог. Так, cd C:\Users перейдет в папку пользователей.
- md NewFolder — создает новую папку.
- rd — удаляет пустую папку. Пример: rd NewFolder удалит папку NewFolder.
- copy — копирует файлы из одного места в другое.
- move — перемещает файлы или папки.
- del — удаляет файлы. Например, del file.txt удалит файл file.txt.
- xcopy — копирует файлы и директории, включая их структуру. Так, xcopy C:\Source D:\Destination /s /e скопирует все файлы и папки из Source в Destination.
- robocopy — более продвинутая версия xcopy, используется для надежного копирования данных. Например, robocopy C:\Source D:\Destination /mir синхронизирует две папки.
Команды для управления пользователями
Команды для управления пользователями предоставляют средства для администрирования учетных записей, настройки групповых прав и управления политиками безопасности. А также позволяют администраторам эффективно управлять пользователями в системе, добавлять новых пользователей, изменять их права и настраивать параметры учетных записей.
- net user — управляет учетными записями пользователей.
- net user UserName /add — добавляет нового пользователя с именем UserName.
- net localgroup — управляет локальными группами пользователей.
- net localgroup Administrators UserName /add — добавляет пользователя в группу администраторов.
- whoami — выводит имя текущего пользователя и информацию о его правах.
- runas — позволяет запускать программы от имени другого пользователя. Так, runas /user:administrator cmd запустит CMD с правами администратора.
- net accounts — управляет параметрами учетных записей, например, минимальной длиной пароля и периодом его действия.
- gpupdate — обновляет групповые политики на локальном компьютере, что полезно для администраторов, управляемых сетей.
- taskview — открывает таймлайн Windows, показывая историю активности пользователя, полезно для управления и поиска ранее использованных файлов и приложений.
- msg — отправляет сообщение пользователям, подключенным к системе. Пример: msg «Система будет перезагружена через 5 минут» отправит сообщение всем пользователям.
Команды для управления безопасностью
Команды для управления безопасностью предназначены для обеспечения защиты данных и управления доступом к файлам и системным ресурсам, что позволяет шифровать файлы, проверять целостность системных файлов и управлять правами доступа.
- cipher — управляет шифрованием файлов на дисках NTFS.
- cipher/e — зашифровывает файлы в указанной директории.
- sfc — проверяет целостность системных файлов и автоматически восстанавливает их при обнаружении повреждений.
- sfc /verifyonly — проверяет системные файлы на наличие повреждений, но не исправляет их автоматически.
- sfc /scannow — выполняет полную проверку системы.
- cacls — изменяет права доступа к файлам. Пример: cacls file.txt /g UserName:F даст пользователю полный доступ к файлу.
- icacls — расширяет возможности команды cacls и предоставляет дополнительные параметры для управления правами доступа.
- takeown — позволяет взять владение файлом или директорией. Так, takeown /f file.txt предоставит доступ к файлам.
- attrib — изменяет атрибуты файлов и папок. Например, attrib +r file.txt сделает файл доступным только для чтения.
Команды для диагностики и устранения неполадок
Команды из раздела помогают находить и устранять неполадки в системе, восстанавливать загрузочные параметры и проверять целостность данных на диске, а также они позволяют решать проблемы, связанные с запуском операционной системы или со сбоями на уровне файловой системы.
- chkdsk — проверяет диск на наличие ошибок и исправляет их. Так, chkdsk C: /f выполнит проверку диска C.
- bootrec — восстанавливает загрузочный сектор.
- bcdedit — управляет параметрами загрузки системы.
- bcdedit /set {current} safeboot minimal — включает безопасный режим.
Команды для скриптинга и автоматизации
Команды, приведенные ниже, предназначены для создания сложных сценариев выполнения команд, что позволяет автоматизировать повседневные задачи и более эффективно управлять процессами.
- for — создает цикл для выполнения команд. Например, for %i in (1 2 3) do echo %i выведет числа 1, 2, 3.
- if — выполняет условное выполнение команд.
- goto — перенаправляет выполнение скрипта к определенной метке.
- call — вызывает другую команду или скрипт.
Команды для управления сетевыми подключениями
Команды для управления сетевыми подключениями предоставляют возможности для настройки, диагностики и оптимизации сетевых параметров и соединений, позволяя управлять IP-адресами, подключаться и отключаться от сетей.
- ipconfig /release — освобождает текущий IP-адрес, назначенный DHCP сервером, что позволяет при необходимости сбросить сетевое подключение.
- ipconfig /renew — обновляет IP-адрес, полученный от DHCP сервера. Часто используется после команды ipconfig /release для восстановления подключения.
- ipconfig /flushdns — очищает кэш DNS, если изменился DNS-сервер или необходимо устранить проблемы с доступом к сайтам.
- ipconfig /displaydns — выводит содержимое кэша DNS, часто используется для диагностики проблем с DNS.
- netsh interface ip set address — используется для назначения статического IP-адреса сетевому интерфейсу. Пример: netsh interface ip set address Ethernet static 192.168.1.100 255.255.255.0 192.168.1.1.
- netsh wlan show drivers — выводит информацию о драйверах беспроводной сети, что полезно при настройке Wi-Fi подключения.
- netsh wlan show interfaces — отображает текущие активные беспроводные подключения и их параметры, например, мощность сигнала.
- netsh wlan connect — подключает к указанной Wi-Fi сети. Для этого нужно ввести: netsh wlan connect name=MyWiFi.
- netsh wlan disconnect — отключает текущее беспроводное подключение.
- netsh advfirewall set allprofiles state — управляет состоянием брандмауэра Windows – netsh advfirewall set allprofiles state off отключает брандмауэр для всех профилей.
- netsh int ip reset — сбрасывает настройки IP стека (TCP/IP) к значениям по умолчанию, помогая при сетевых неполадках.
- route add — добавляет маршрут в таблицу маршрутизации. Например, route add 192.168.2.0 mask 255.255.255.0 192.168.1.1 добавит маршрут для подсети 192.168.2.0 через шлюз 192.168.1.1.
- route delete — удаляет указанный маршрут из таблицы маршрутизации.
- netsh interface show interface — выводит список всех сетевых интерфейсов в системе, включая их состояние и тип.
- net view — отображает список компьютеров в локальной сети – net view \\server покажет общие ресурсы на указанном сервере.
- net use /delete — удаляет существующее подключение к сетевому ресурсу. Так, net use Z: /delete отключает сетевой диск Z:.
- ftp — открывает FTP-клиент для передачи файлов между локальной и удаленной системами. Например, по команде ftp ftp.example.com ПК подключится к FTP-серверу.
- telnet — используется для подключения к удаленным системам через Telnet-протокол. Так, telnet example.com 23 подключит ПК к серверу на порту 23.
- getmac — выводит MAC-адреса всех сетевых интерфейсов компьютера.
Команды для управления печатью
В этом разделе команды для управления печатью позволяют эффективно управлять процессом печати (включая очередью на печать), настройками принтеров и заданиями на печать.
- print — отправляет файл на печать. Например, print C:\Documents\file.txt отправит текстовый файл на принтер по умолчанию.
- rundll32 printui.dll,PrintUIEntry — открывает диалоговое окно для установки или управления принтерами – rundll32 printui.dll,PrintUIEntry /in /n\\server\printer установит сетевой принтер.
- net print — отображает список заданий на печать – net print \\server\printer покажет очередь печати на указанном принтере.
- net stop spooler — останавливает службу диспетчера очереди печати (spooler), особенно когда требуется устранить зависшие задания печати.
- net start spooler — запускает службу диспетчера очереди печати после её остановки.
- wmic printer list brief — выводит список установленных принтеров с краткой информацией о каждом из них.
- wmic printer where default=true get name — выводит имя принтера, установленного по умолчанию.
- wmic printer where name=’PrinterName’ delete — удаляет указанный принтер из системы.
- wmic printerconfig — отображает информацию о конфигурации принтера, включая его настройки и параметры печати.
- cscript prnjobs.vbs — используется для управления заданиями печати через скрипт prnjobs.vbs, который можно использовать для удаления, приостановки или возобновления заданий.
Дополнительные команды в Windows
В дополнение к основным инструментам для управления системой, командная строка Windows предоставляет ряд дополнительных команд, которые расширяют возможности администрирования и диагностики.
- wevtutil — управляет журналами событий Windows. Например, wevtutil qe System выведет события из системного журнала.
- tzutil — управляет настройками часовых поясов. tzutil /s Pacific Standard Time установит часовой пояс на Тихоокеанское стандартное время.
- taskkill — завершает процесс по его PID или имени. Так, taskkill /F /PID 1234 завершит процесс с PID 1234.
- powercfg /hibernate off — отключает режим гибернации.
- powercfg /energy — создает отчет об использовании энергии системой.
Home » KB » SysAdmin » Windows CMD Commands: Mastering the Command Prompt
The Windows operating system includes over 280 CMD (Command Prompt) commands. These commands enable users to interact directly with the OS and perform various troubleshooting and IT automation tasks.
Many CMD commands work on specific Windows desktop versions, while others are only available for Windows Server editions.
This extensive guide lists all Windows CMD commands and provides hands-on examples of the most commonly used ones.
Prerequisites
- Access to the command prompt (CMD).
- Administrator privileges (for some commands).
Essential Command Prompt Commands
Commands are built-in programs that run through the Command Prompt program. The main use for commands is to automate various tasks, such as user provisioning and other routine actions.
Below is an overview of essential Windows CMD (Command Prompt) commands. Every command has a brief explanation and an example use case.
1. arp Command
The arp (Address Resolution Protocol) command shows and modifies entries in the ARP cache. The cache contains one or multiple tables that map IP addresses to physical (MAC) addresses for devices on the local network.
The syntax for the command is:
arp [options] [address]
Without any parameters, the arp command shows the help window.
To show the ARP cache table, run the following command:
arp -a
The output lists all the current ARP entries grouped by network interface.
2. assoc Command
The assoc (association) command lists and modifies file extension associations on the system. The syntax for the command is:
assoc .[extension]=[filetype]
Without any parameters, the command prints the current file extension associations.
Use the assoc command to view, change, or remove file associations. For example, to view the .log file associations, enter:
assoc .log
Change the file association with:
assoc .log=txtfile
Alternatively, to remove all file associations for files with the .log extension, use:
assoc .log=
Add a space after the equals sign to remove the association.
3. attrib Command
The attrib (attribute) command displays or changes file attributes. The possible attributes are:
- R — Read-only.
- H — Hidden.
- S — System file.
The syntax for the attrib command is:
attrib [+/-] [attribute] [file_or_directory]
Use the plus sign (+) to set an attribute or the minus sign (-) to remove an attribute from a file. Without any options, the command shows the file attributes in the current directory.
To set a file to have the read-only (R) and hidden (H) attributes, use the following command:
attrib +R +H sample_file.txt
To make a file visible, remove the hidden (H) attribute:
attrib -H sample_file.txt
The minus (-) removes the attribute from the file and returns the file to the default visible state.
4. bcdboot Command
The bcdboot (Boot Configuration Data Boot) command sets up a system partition by copying BCD files into an empty partition.
The syntax for the command is:
bcdboot [path]
For example, to copy the BCD files into C:\Windows, use:
bcdboot C:\Windows
The message confirms the file has been created.
5. cd Command
The cd (change directory) command shows or changes the current location. The syntax for the command is:
cd [directory]
The directory parameter is optional, and without it, the command prints the current working directory.
For example, to change the location to a directory named Public, add the directory name after the command:
cd Public
The prompt reflects the change and shows the new location.
To change the location to a different drive, add the /d option before the path. For example, to change to drive S:\ use:
cd /d S:
cd only displays the path without switching to the specified drive if the /d option is not used.
To change to the parent directory one level up, use the following shortcut:
cd ..
The current directory changes to the parent of the previous location.
6. chkdsk Command
The chkdsk command scans the local file system and metadata for errors. The syntax for checking a disk is:
chkdsk [volume] [options]
Without additional parameters, chkdsk displays the current disk state without fixing any errors.
Additional parameters allow you to fix errors on a disk, for example, the /f option:
chkdsk [volume] /f
The command attempts to fix errors on the disk. If the disk is in use, run the check on the next system restart. Interrupting chkdsk while it’s running is generally safe, but it’s recommended to complete the scan later to address potential data corruption.
7. choice Command
The choice command prompts a user to choose an answer from a list of options. Without any parameters, the command prompts the user to choose between Y and N options.
Additional options control the number of choices and the prompt text. For example, to add a third choice, use the /c parameter and list the three option names:
choice /c ync
Insert additional text to explain the available options with the /m parameter. For example:
choice /c ync /m "Yes, No, Continue"
In all cases, the command returns the choice index and exits.
8. cipher Command
The cipher command shows and modifies the encryption status of files or directories on NTFS file systems. The command syntax is:
cipher [options] [file_or_directory]
Without any options, cipher shows the encryption state for all files and directories in the current location. The U represents «unencrypted,» whereas E is «encrypted.»
To encrypt a file in the current directory, use the /e parameter:
cipher /e [file name]
The file’s indicator changes from U to E to mark the file as encrypted.
9. clip Command
The clip command copies a command output or file contents to the Windows clipboard. The syntax for copying a command’s output in CMD is:
[command] | clip
For example, to copy the current directory path, pipe the cd command to clip:
cd | clip
Paste the contents anywhere in the window using CTRL+V (or right-click in CMD).
To copy the contents of a file, use redirection:
clip < [filename]
For example, to copy the contents of a sample.txt file to the clipboard, run:
clip < sample.txt
The file’s contents are saved to the clipboard, so you can paste them anywhere.
10. cls Command
The cls command clears the text in a command prompt window and returns a blank surface. Use the command to clear the screen contents.
Note that the previous contents and output cannot be restored.
11. cmd Command
The cmd command starts a new instance of the command interpreter. Use the following syntax to run the command:
cmd [options] [command]
Without additional parameters, the cmd command shows the current cmd.exe program version.
Use cmd to run commands without affecting the current session. For example, to test a command and return to the current command interpreter session, use the /c parameter:
cmd /c cd ..
The new interpreter changes the directory. However, the /c tag ensures the interpreter returns to the original session, and the directory stays unchanged.
To run a command and stay in the new session, use the /k parameter:
cmd /k cd ..
The /k parameter switches to the new session and runs the cd command to switch to the parent directory.
12. color Command
The color command changes the default console background and text colors. The command syntax is:
color [background][font]
The color attributes are hexadecimal numbers from 0 to f. The help window displays all the possible color options:
help color
For example, to change the background to blue (1) and the font to light aqua (b), run:
color 1b
To return to the default console colors, run the color command without options.
13. comp Command
The comp command compares the contents of two files. The program inspects file bytes and outputs characters where the two files differ.
The syntax for the command is:
comp [file 1] [file 2] [options]
Without any options, the comp command starts an interactive prompt to enter file names and additional options.
To demonstrate how the command works, compare two text files with the following contents:
- sample_file_1.txt contains test
- sample_file_2.txt contains text
Run the comp command and provide the two file names:
comp sample_file_1.txt sample_file_2.txt
The output prints the comparison error as characters in hexadecimal format and asks to compare more files (enter N to exit).
To print the comp results in human-readable format, use the /a option:
comp /a sample_file_1.txt sample_file_2.txt
The comparison fails at character s in the first file and character x in the second file.
14. compact Command
The compact command is a built-in feature for compressing files and folders. The syntax for the command is:
compact [options] [file_or_directory]
Without any options or parameters, compact displays the compression state in the current directory.
To compress a file, use the /c parameter and provide the file name:
compact /c sample_file.txt
To uncompress a file, use the /u parameter:
compact /u sample_file_1.txt
The sample_file_1.txt file is returned to its previous, uncompressed state. Use the compact command to save disk space and compress large files and directories.
15. copy Command
The copy command copies one or multiple files from one location to another. The command syntax is:
copy [options] [source] [destination]
For example, to copy a file’s contents into a new file in the same location, use:
copy sample_file.txt sample_file_copy.txt
The command creates the new file and copies all the contents from the source file.
16. date Command
The date command shows and modifies the current date on the system. Without any parameters, the command prints the current date and requests to enter a new date:
date
Enter the date as mm-dd-yyyy to change the current date on the system or exit with CTRL+C.
Use the /t parameter to avoid modifying the system state and only print the current date:
date /t
The command shows the day of the week and the current date.
17. defrag Command
The defrag (defragmentation) command finds and aggregates fragmented files on the system. The command reduces unnecessary empty data blocks and improves system performance.
The syntax for the defrag command is:
defrag [volumes] [options]
For example, to defragment the C:\ drive, run:
defrag C:\ /u /v
The /u parameter displays progress updates, while /v provides a verbose output. These parameters are optional.
18. del and erase Commands
The del and erase commands delete one or more files. The syntax for the commands is:
del [options] [file(s)]
erase [options] [files(s)]
Both commands permanently delete the specified file or files from a disk and are irretrievable.
For example, to delete a file with the name sample.txt, run:
del sample.txt
Or alternatively:
erase sample.txt
To avoid accidental deletion, use the /p parameter:
del /p sample.txt
The output shows a prompt with the file name and requires confirmation before deleting the file.
19. dir Command
The dir (directory) command lists directory contents, including files and subdirectories. The syntax for the command is:
dir [drive][path][filename] [options]
The dir command without options shows information for the current directory.
To show the C:\ drive contents, run:
dir C:\
The output shows the following information:
- Volume label and drive letter.
- Volume serial number.
- Directory contents with modification time.
- File and directory count with their combined size.
20. diskpart Command
The diskpart command is a disk partitioning tool used to create, delete, and format partitions.
Enter the following command to access the diskpart interface:
diskpart
Once in diskpart, use the following command to list all disks:
list disk
The interface displays all available disks on the system and allows you to use diskpart commands to manage partitions.
21. DISM Command
The Deployment Imaging Service and Management (DISM) command is used to service and manage Windows images. It required administrator privileges. The command is useful for repairing system files or preparing images for deployment.
The general syntax for the DISM command is:
DISM /[target_image] /[operation] /[option]
For example, to repair corrupted files on the current Windows instance, use the following command:
DISM /Online /Cleanup-Image /RestoreHealth
DISM is often used alongside the sfc command to ensure system integrity.
22. doskey Command
The doskey command starts the Doskey.exe program for the previously entered commands. The command helps recall command history and create macros.
For example, to see the command history from the current command prompt session, run:
doskey /history
The output shows all the commands from the CMD session from oldest to newest.
23. driverquery Command
The driverquery command displays the installed device drivers and their information. The command works for both local and remote access machines.
The syntax for the command is:
driverquery [options]
Without options, driverquery shows device drivers on the local machine. Additional options control the output format or allow users to query remote machine drivers.
24. echo Command
The echo command prints a message to the console and controls command echoing in scripts. The syntax for the command is:
echo [message]
Without parameters, the command shows the current settings.
To display a «Hello, world!» message, enter:
echo "Hello, world!"
The echo command often appears in scripts to print useful information while the script runs.
25. exit Command
The exit command ends the current batch script or the command interpreter session. The syntax for the command is:
exit [/b]
- Use the
/bparameter to exit a batch script but keep the Command Prompt session open. - Without the
/boption, theexitcommand closes the Command Prompt session entirely.
26. fc Command
The fc (file compare) command compares two or more files and displays their differences.
The syntax for fc is:
fc [options] [file1] [file2]
For example, to compare two sample files, sample_file_1.txt and sample_file_2.txt, run:
fc sample_file_1.txt sample_file_2.txt
The command prints the file contents, indicating a difference between the two files.
27. find Command
The find command searches for a string within a file and prints matching lines. The command syntax is:
find ["string"] [file]
For example, to search for the string «text» in a file, use:
find "text" [file]
The command looks for an exact match and returns the file name along with the line of text that contains the string. If a file does not contain the text, the command returns the file name without the text.
28. findstr Command
The findstr (find string) command performs a similar task to the find command. The command returns the whole line where the text is located without the file name. This feature makes it more convenient for use in scripts.
The command syntax is:
findstr ["string"] [file]
For example, to find a string «text» in a file, run:
findstr "text" [file]
If the command does not return a result, the string is not in the file.
29. ftype Command
The ftype (file type) command shows and changes a file type and extension association. The command syntax is:
ftype [filetype]=[open_command]
The filetype parameter is the file to show or modify (such as txtfile), while the open_command option is a string that calls a program to read the file type. The open_command string substitutes the file name into the open command to run a file in the provided program.
Without any options, ftype prints all file types and extension associations.
To show the current file type and extension association for text files, enter:
ftype txtfile
To remove file type association, append an (=) sign:
ftype txtfile=
The command omits the program for opening files and removes the program association.
30. getmac Command
The getmac command retrieves MAC addresses for all network cards on the computer or in the network. Additionally, it displays the network transport protocols associated with each MAC address.
The syntax is:
getmac [options]
Adding options provide detailed information about a remote computer or control the output display. For example, to show the MAC addresses in the CSV format, use:
getmac /fo csv
Use the command to parse the MAC address to a network monitoring tool or to check the protocols on network adapters.
31. help Command
The help command shows detailed information about a specific command. Without any parameters, help lists all available system commands.
The syntax for the command is:
help [command]
For example, to view the help menu for the cd command, run:
help cd
Use any key to go through the pages if the help page is larger than the command line window. Alternatively, press CTRL+C to exit.
Note: For non-system commands, use the following format to see the help window:
[command] /?
32. hostname Command
The hostname command displays a machine’s host name. Run the command to see the name of the current machine:
hostname
The command does not have options, and providing additional parameters results in an error. The hostname command is available for systems with TCP/IP installed on a network adapter.
33. ipconfig Command
The ipconfig (IP configuration) command is a networking tool that shows all current TCP/IP network configuration information. The command also refreshes DHCP and DNS settings.
The syntax for the command is:
ipconfig [options]
Omitting options shows the basic TCP/IP configuration for all adapters:
ipconfig
To show the full TCP/IP configuration for all adapters, run:
ipconfig /all
Renew the DHCP IP address for the local area connection with:
ipconfig /renew Local Area Connection
To flush the DNS cache, use:
ipconfig /flushdns
Use the command when troubleshooting DNS and network connectivity issues.
34. label Command
The label command shows, changes, or removes the volume label (name) of a disk. The command requires administrator privileges to perform any changes.
Without any options, the label command shows the label for the C:\ drive and starts a prompt to change the name:
label
Press Enter to remove the label, or enter a new name to change the current label name. Confirm the change with Y or press N to keep the existing name.
35. makecab Command
The makecab command creates a cabinet (.cab) file. Cabinet files are an archive format specific to Windows systems with support for lossless data compression and archive integrity.
Use the following syntax to create .cab files with the makecab command:
makecab [options] [source] [destination]
For example, to create a sample_cab.cab file in the current directory and add a sample_file.txt file to the archive, use:
makecab sample_file.txt sample_cab.cab
The output shows the compression progress and exits when done.
36. md and mkdir Commands
The md and mkdir (make directory) commands create a new directory or subdirectory. The command syntax is:
md [path]
mkdir [path]
For example, to make a new subdirectory called Subdir in the current location, run:
mkdir Subdir
The command extensions enable md and mkdir to create a directory tree:
md Subdir\Subsubdir
The command immediately creates all intermediate subdirectories in the specified path.
37. mklink Command
The mklink (make link) command creates a hard or symbolic link to a file or directory. The command requires administrator privileges to run and uses the following syntax:
mklink [options] [link] [target]
Without any additional options, the mlink command creates a symbolic link to a file. For example:
mklink my_link sample_file.txt
To create a hard link instead of a symbolic link, use the /h parameter:
mklink /h my_link sample_file.txt
Create a symbolic link to a directory with the /d parameter:
mklink /d \Docs \Users\user1\Documents
The dir command shows the links in the directory listing. To enter the directory, use the cd command and treat the link as a regular directory (cd Docs).
38. more Command
The more command is a Windows CMD utility for displaying long documents or outputs one screen at a time. To use more with a command, use the pipe (|) character:
[command] | more [options]
Alternatively, use the command to display long files page by page:
more [path]
For example, to view the output of the help cd command one screen at a time, use:
help cd | more
Press Enter to go to the following line and Space to go to the next page. To exit, press q.
39. mountvol Command
The mountvol command creates, removes, or shows a volume mount point. Mounting a volume makes data on a storage device available for local users through the file system.
The command syntax is:
mountvol [path] [volume_name]
The command does not require a drive letter to link a volume. Without any parameters, the mountvol command shows the help menu, mount points, and possible volume names.
For example, to list the volume name and current mount point for the C:\ drive, enter:
mountvol C:\ /l
The output shows the Globally Unique Identifier (GUID) for the volume, which uniquely identifies the volume.
40. move Command
The move command transfers files or directories from one location to another. The syntax for the command is:
move [options] [source] [destination]
The source and destination are either a folder or a file. The move command renames a file if the source and destination locations are the same but have different file names.
For example, the following command renames a file named sample_file.txt to file.txt:
move sample_file.txt file.txt
Provide the full path to move a file to another location:
move C:\Users\Public\Downloads\my_file.txt C:\Users\Public\Desktop\my_file.txt
When overwriting an existing file, the command prompts for confirmation unless the command runs as part of a batch script.
41. msiexec Command
The msiexec program runs the Windows Installer program for installing, managing, and removing .msi software packages. The command syntax is:
msiexec [options] [path_to_package]
The program features various install, display, update, and repair options. Without any options, the msiexec command opens a window to show the command information.
For example, to perform a normal installation of a .msi package, run:
msiexec /i "C:\example.msi"
The /i option indicates a normal installation of the .msi package located at the provided path.
42. msinfo32 Command
The msinfo32 command opens the System Information window, which displays detailed information about the system.
The command syntax is:
msinfo32 [options]
Additional options filter the information or export data into specific file formats. For example, to export all system information into an .nfo file, use:
msinfo /nfo sysinfo.nfo
The command automatically appends the .nfo extension if omitted.
43. mstsc Command
The mstsc command launches the RDC (Remote Desktop Connection) program to connect to a remote machine. Use the command for remote connection or to alter an existing .rdp file.
The command syntax is:
mstsc [options] [file]
For example, to start an RDC session in full-screen mode, use this command:
mstsc /f
To edit an existing connection, use the /edit parameter and provide the file name:
mstsc /edit example.rdp
User-created .rdp files are stored in the Documents folder by default.
44. net Commands
net commands are a set of tools for managing various network aspects, such as users and network services.
The command syntax is:
net [subcommand] [options]
Without additional parameters, the net command shows all available subcommands with a short description.
Use the net start command to list all running Windows services:
net start
To stop a service, use the following command:
net stop [service]
View the login and password requirements for a user with the following:
net accounts
Display additional help for a subcommand using the following syntax:
net help [subcommand]
The output shows a help window with detailed information for the provided subcommand.
45. netstat Command
The netstat (network statistics) command is an essential command for network administrators. The command lets you view connection details and various network statistics.
The basic syntax for the command is:
netstat [options]
The command displays active TCP connections when used without options. The output shows the protocol, local and foreign addresses, and the TCP connection state.
Add the -a option to display all active TCP connections and listening TCP and UDP ports:
netstat -a
Use the command to scan for open ports or to check the port protocol type.
46. nslookup Command
The nslookup command is a DNS diagnostic tool to query DNS records for web servers. The command features a non-interactive mode for looking up a single piece of information and an interactive mode for looking up additional data.
The syntax for nslookup is:
nslookup [host] [command] [options]
Without any options, nslookup enters interactive mode. To find DNS records for a specific domain name, use:
nslookup [domain]
The output prints the A records for the provided domain.
47. path Command
The path command modifies the PATH environment variable. The variable contains a set of directories that point to executable files.
The command syntax looks like the following:
path [location]
Without any parameters, path shows the current state of the PATH variable.
To add multiple locations to PATH, separate each location with a semicolon (;) as in the following example:
path [location 1]; [location 2]
Both locations append to the variable.
48. ping Command
The ping command is an essential network troubleshooting tool used to test connectivity with another machine by sending ICMP request messages.
The syntax for the command is:
ping [options] [host]
For example, to check connectivity to the phoenixNAP website, use:
ping phoenixnap.com
The output prints corresponding reply messages and round-trip times. Use the command to check for connectivity and name resolution issues.
49. powercfg Command
The powercfg (power configure) command runs the powercfg.exe program to manage system power plans. It also helps troubleshoot battery life and energy efficiency problems on a device.
The command syntax is:
powercfg [options] [arguments]
To list available power plans on a device, use:
powercfg /list
The output lists all power schemes on the system. The active power scheme has an asterisk (*).
50. powershell Command
The powershell command opens a PowerShell session within the CMD to provide access to advanced scripting and management features.
Enter the following command to invoke PowerShell from CMD:
powershell
You can now run PowerShell commands. For example, the following PowerShell command lists running processes:
Get-Process
The output displays a list of active processes. To leave the PowerShell prompt and return to the CMD, type:
exit
Using PowerShell through CMD lets you quickly switch to a more robust scripting environment without leaving the session window.
51. prompt Command
The prompt command customizes the CMD prompt display to a specified string. By default, the prompt shows the current location and the greater-than sign (>).
The command syntax is:
prompt [string_and_variables]
The prompt command supports various variables to add special characters or features. For example, to change the prompt to an arrow, use:
prompt --$g
The $g variable represents the greater-than sign (>). The prompt custom stays active during the command-line session.
52. rd and rmdir Commands
The rd and rmdir commands remove an empty directory from the system. The syntax for the commands is:
rd [path]
rmdir [path]
Attempting to delete a directory with files results in an error message. Add the /s parameter to delete a directory with subdirectories and files:
rd /s [path]
The command deletes the complete subdirectory tree and all files.
53. ren and rename Commands
The ren and rename commands rename files or directories. The syntax for the two commands is:
ren [path][old_name] [new_name]
rename [path][old_name] [new_name]
The commands do not allow moving the files to a different location. Wildcard characters work for multiple files. For example, to change all .txt files to .c files, use:
ren *.txt *.c
The asterisk (*) wildcard matches all .txt files in the current directory and renames the files to have the .c extension.
54. robocopy Command
The robocopy command is a powerful tool for copying files and directories. The syntax for the command is:
robocopy [source] [destination] [file] [options]
The main benefit when using robocopy is the /mt parameter for higher-performance multithreading. Additionally, the /z parameter lets you restart a transfer in case of interruptions.
An example transfer looks like the following:
robocopy C:\Users\user\Downloads C:\Users\user\Documents database.db /mt /z
Use the command for large file transfers that are sensitive to interruptions.
55. route Command
The route command shows and alters entries in the local routing table. The command syntax is:
route [options] [command] [value]
Available commands include:
add— Adds a route entry to the table.change— Modifies an entry in the table.delete— Removes a route from the table.print— Displays a route or routes.
For example, to print all routes from the table, use:
route print
The output shows the interface list, as well as the IPv4 and IPv6 routing tables.
56. sc Command
The sc (service control) command allows users to manage Windows services without opening the Services Manager. Users can start, stop, query, and configure services from the command line.
The syntax for the sc command is:
sc query [service_name]
For example, to check the status of the Windows Update service, run:
sc query wuauserv
The output shows details about the service, including its status.
57. schtasks Commands
The schtasks command schedules commands or programs to run on the system at specified times or periodically and is often used to set up cron jobs. The syntax for the commands is:
schtasks /[subcommand]
The following subcommands are available:
change— Modifies existing properties of a task.create— Creates a new task.delete— Removes a task.end— Stops a program started by a task.query— Prints scheduled tasks on the machine.run— Starts a scheduled task.
For example, to show currently scheduled tasks on the system, use:
schtasks /query
The output displays task names, next run times, and task statuses.
58. set Command
The set command shows, sets, and removes environment variables in the CMD. The syntax for the command is:
set [variable]=[value]
Without additional parameters, the set command shows all environment variables.
The variables are available to use with any command. For example, to create a new CMD variable called message, use:
set message="Hello, world!"
Reference the variable using the following syntax:
echo %message%
Encasing the variable in the percent signs (%) reads the value and outputs it to the screen.
Note: The variables do not persist and are only valid for the current command-prompt session.
59. sfc Command
The sfc (System File Checker) is an administrator command for checking protected file version integrity. It also replaces incorrect overwritten protected files with the correct file version.
The syntax for the command is:
sfc [options] [file_or_directory]
For example, to scan the system and repair all files, use:
sfc /scannow
The command scans all protected system files and repairs problematic files when possible.
60. shutdown Command
The shutdown command restarts or shuts down a local or remote computer. The command syntax is:
shutdown [options]
Without any arguments, the shutdown command opens the help menu. To restart the computer, use the /r option:
shutdown /r
To shut down without restarting, use the /s argument:
shutdown /s
In both cases, the shutdown is not immediate. To cancel the action, use the /a option:
shutdown /a
The option ensures that a previously executed shutdown command is aborted.
61. sort Command
The sort command allows sorting provided data from a file or user input. Additional options control the sorting mechanism and from which point to start sorting.
To use the command interactively, do the following:
1. Run sort without any options.
2. Enter a new word in each line.
3. Press CTRL+Z and Enter at the end of the list to sort the input values alphabetically.
Alternatively, use the sort command on files:
sort sample_file.txt
The command sorts the file contents and prints the result to the console.
62. start Command
The start command opens a new Command Prompt window according to the specified options. The command syntax is:
start [title] [options]
For example, to open a new Command Prompt session with the title «Hello, world!» and set the path to C:\. enter the following command:
start "Hello, world!" /d C:\
A new CMD window opens with the starting path on the C:\ drive and a custom title.
63. systeminfo Command
The systeminfo command displays detailed system information about the OS and computer, including hardware properties. The command works on both local and remote machines.
Use the command without options to show the local system information:
systeminfo
Additional options allow you to retrieve system information for remote computers or control the output format. For example, show the output in CSV format with:
systeminfo /fo csv
Different formats enable you to effectively parse the information through scripts.
64. takeown Command
The takeown (take ownership) command allows an administrator account to take ownership of a file. It provides access to a file for an administrator and makes the administrator the owner.
Add the /f option and specify the file name:
takeown /f [file]
The administrator now has full permissions over the file.
65. taskkill Command
The taskkill command terminates a running process or task on the Windows system through the command line. It is useful for forcefully ending unresponsive processes.
The syntax for the command is:
taskkill [options] [task_or_process]
A common way to end a task is to find the process ID (PID) with the tasklist command and end the process with:
taskkill /pid [Process ID]
The command finds the process by ID and forcibly stops it.
66. tasklist Command
The tasklist command shows all running processes on a local or remote computer and their memory usage. It helps identify and reference specific processes.
The syntax for tasklist is:
tasklist [options]
Without additional options, the command shows all currently running processes.
The image name and PID are unique identifiers for a process. The final column shows the memory usage for a process. This is a good indicator for identifying processes that slow down the system.
67. telnet Command
The telnet command is a Windows tool for bidirectional CLI communication. The tool uses the Telnet protocol to send messages and enable an interactive communication channel with remote devices.
The syntax for the command is:
telnet [command] [option]
See our detailed guide for using Telnet on Windows.
68. time Command
The time command manages and displays the current system time. Without any options, the command prints the current time and prompts to enter a new time:
time
Enter a new time to change the system time or exit the prompt using CTRL+C. Use the /t option to avoid making modifications:
time /t
The command prints the current time and returns to the command line.
69. timeout Command
The timeout command pauses the command line for a specified number of seconds. The syntax for the command is:
timeout /t [seconds]
For example, to pause the interpreter for ten seconds, run:
timeout /t 10
The output counts down and returns to the command line. Press any key to interrupt the timeout earlier. Use the command in scripts to wait for execution between two commands.
70. title Command
The title command is a simple utility for changing the title of the Command Prompt window. The syntax is:
title [string]
For example, to set the title to "Hello, world!", use:
title "Hello, world!"
The CMD window title changes to the provided string. Use the command when running multiple batch scripts to distinguish between different command prompts.
71. tracert Command
The tracert (traceroute) command is a networking tool that maps the path from a local computer to a destination. It sends ICMP messages with increasing TTL values to map routers along the path.
The syntax for tracert is:
tracert [option] [destination]
For example, to trace the path to phoenixnap.com, use:
tracert phoenixnap.com
Alternatively, use the IP address of the destination.
The output shows the hops between the source and destination, providing an IP address and name resolution where applicable. Use the command to discover connectivity issues to a host.
72. tree Command
The tree command displays the contents inside a drive or directory in a tree-like structure. The syntax is:
tree [option] [path]
Without options, the tree command displays the directory structure of the C:\ drive.
73. type Command
The type command displays the contents of a file directly in the Command Prompt without modifying it.
The syntax for the type command is:
type [file_path]
For example, to show the contents of the file called sample_file.txt, run:
type sample_file.txt
The output prints the file’s contents to the command line. Use this command to preview files directly in the command prompt.
74. tzutil Command
The tzutil (time zone utility) command modifies and displays the system’s timezone settings.
Display the current time zone with:
tzutil /g
The output shows the time zone ID. List all available time zone IDs with:
tzutil /l | more
The more command helps truncate long outputs. Use the /s parameter and provide the time zone ID to change the system timezone.
75. ver Command
The ver command is a simple utility to show the operating system version. To display the OS version, enter:
ver
The output displays the OS version and returns to the command line.
76. vol Command
The vol command prints the disk volume label and serial number. The syntax for the command is:
vol [drive]:
Without a specified drive, the vol command shows information for the currently selected drive.
77. where Command
The where command locates a file based on the search pattern and displays its path in the command line. The syntax for the command is:
where [options] [search_location] [filename]
Omitting the location searches for the file in the current directory without going through subdirectories. To perform a recursive search, add the /r parameter. For example:
where /r C:\ sample_file.txt
The command searches the C:\ drive and all subdirectories. If the file is found, the command returns the its full location path.
78. whoami Command
The whoami command shows the current user’s domain and username. The syntax for the command is:
whoami [option]
Without options, the command shows the domain and user name.
Add the /all parameter to show detailed information for the current user:
whoami /all
The user’s name, security ID, groups, and privileges are displayed.
79. wmic Command
The wmic (Windows Management Instrumentation Command-line) is used to query hardware details, software configurations, and access other system information and settings.
The syntax for the wmic command is:
wmic [alias] [where_clause] [get/set/call] [property]
- alias — Specifies the area of the system to query (e.g., cpu, os, product).
whereclause — Adds conditions to narrow down the query.- operation — Defines the action, typically
get(retrieve),set(modify), orcall(execute an action). - property — Lists specific properties to display, retrieve, or modify.
For example, to get a list of all installed applications, enter:
wmic product get name
The output shows a list of installed programs.
80. xcopy Command
The xcopy command copies files, directories, and subdirectories from one location to another. The syntax for the command is:
xcopy [source] [destination] [options]
For example, use the following command to copy contents from one location to another, including subdirectories (even if empty):
xcopy [source] [destination] /s /e
The /s parameter copies subdirectories, while /e includes empty directories. If any files with the same name exist in the destination, the command prompts before overwriting.
Windows CMD Commands Cheat Sheet
The essential commands are available in a single-page cheat sheet in PDF format. Save the cheat sheet for future use and reference by clicking the Download Windows CMD Commands Cheat Sheet button below.
Other Command Prompt Commands
The commands listed in the table are used less frequently by regular Windows users. IT professionals rely on these commands to manage Windows Servers, troubleshoot system processes, configure network settings, and perform other specialized tasks in a business environment:
| Command | Description | Compatibility |
|---|---|---|
accept |
Allow the server to accept files or services from the network. | Windows XP, Windows Server 2003 |
addusers |
List or add users in a batch. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
adprep |
Prepare a server for Active Directory installation. Server versions only | Windows Server 2003 and later |
auditpol |
Set and display audit policies on a system. | Windows 7, Windows 8, Windows 10, Windows 11 |
autoconv |
Configure automatic file-system conversion during a system restart. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
autofmt |
Format media for an automatic conversion. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
bcdedit |
Manage boot configuration data (BCD). | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
bdehdcfg |
Configure and prepare a hard drive for BitLocker Drive Encryption. | Windows 7, Windows 8, Windows 10, Windows 11 |
bootsect |
Update the master boot code for hard disk partitions to switch between bootloaders. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
call |
Call a batch file from another batch file. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
certmgr |
Manage certificates for a computer, service, or user. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
certreq |
Manage certificate requests. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
certutil |
Manage certificates and certificate stores. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
change |
Adjust Terminal Server settings, logons, and COM port mappings. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
chcp |
Set or display the active code page number. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
chdir |
Change the current directory or display its name. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows NT, Windows 10, Windows 11 |
checknetisolation |
Set up network isolation testing for Microsoft Store apps. | Windows 8, Windows 10, Windows 11 |
chglogon |
Enable or disable logons on a terminal server. | Windows XP, Windows Server 2003 |
chgport |
Display or change COM port mappings for DOS applications. | Windows XP, Windows Server 2003 |
chgusr |
Modify the install mode for the terminal server. | Windows XP, Windows Server 2003 |
chkntfs |
Modify settings or display the disk check at startup. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
cmdkey |
List, create, and delete stored passwords and usernames. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
convert |
Convert FAT volumes to NTFS. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
cscript |
Run scripts from the command line. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
dcpromo |
Promote or demote a domain controller. Server versions only | Windows Server 2000, 2003, 2008 |
diantz |
Compress files for distribution. | Windows XP, Windows Vista, Windows 7 |
diskperf |
Enable or disable disk performance counters. | Windows XP, Windows Server 2003 |
diskraid |
Configure and manage RAID arrays. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
dism |
Manage Windows images. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
diskshadow |
Create and manage shadow copies of disks. | Windows Server 2008, Windows 7, Windows 8, Windows 10, Windows 11 |
dispdiag |
Dump the contents of the Windows display log. | Windows 7, Windows 8, Windows 10, Windows 11 |
djoin |
Provision a computer account in the Windows Active Directory (AD) and join the computer to a domain. | Windows 7, Windows 8, Windows 10, Windows 11 |
dsadd |
Add objects to the Windows Active Directory (AD). Server versions only | Windows Server 2003 and later |
dsget |
Display object properties in the Windows Active Directory (AD). Server versions only | Windows Server 2003 and later |
dsquery |
Find objects in the Active Directory. Server versions only | Windows Server 2003 and later |
endlocal |
End localization of environment changes in a batch file. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
erase |
Delete one or more files. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows 10, Windows 11 |
esentutil |
Utility for managing Extensible Storage Engine (ESE) databases. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
eventcreate |
Create a custom event in the event log. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
expand |
Expand one or more compressed files. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
finger |
Display information about a user on a specified remote computer. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
fltmc |
Manage system filter drivers. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
fondue |
Install optional Windows features. | Windows 8, Windows 10, Windows 11 |
for |
Run a specified command for each file in a set or directory. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows 10, Windows 11 |
forfiles |
Select a file or set of files and execute a command on that file. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
format |
Format a disk for use with Windows. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows 10, Windows 11 |
fsutil |
Perform tasks related to file systems, such as managing file system quotas. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
ftp |
Transfer files to and from a remote network using FTP. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
goto |
Instruct a batch program to jump to a labeled line. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows 10, Windows 11 |
gpresult |
Show Group Policy settings and RSoP for a user or device. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
gpupdate |
Update Group Policy settings. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
hwrcomp |
Compile handwriting recognition data. | Windows XP, Windows Vista, Windows 7 |
hwrreg |
Register handwriting recognizer. | Windows Vista, Windows 7 |
icacls |
Show or modify access control lists for files and directories. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
if |
Perform conditional processing in batch files. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows 10, Windows 11 |
inuse |
Replace files used by the operating system. | Windows XP |
irftp |
Send files over an infrared connection. | Windows XP, Windows Vista |
iscsicli |
Manage iSCSI sessions and devices. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
klist |
List Kerberos tickets for the current logon session. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
ksetup |
Configure Kerberos settings and realm information. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
ktmutil |
Control Kernel Transaction Manager (KTM) resource managers. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
licensingdiag |
Generate a licensing diagnostics report. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
lodctr |
Use to update Performance Monitor counter names and to explain text for an extensible counter. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
logman |
Schedule performance counters and event trace sessions. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
logoff |
Log off a user from a session. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
lpr |
Send a file to a computer or printer-sharing device. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
lpq |
Show the status of a printer queue for a computer or printer. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
manage-bde |
Configure BitLocker Drive Encryption. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
mode |
Configure a system device, like a port or printer. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
mofcomp |
Compile Managed Object Format (MOF) files. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
mount |
Mount a network file system. Requires additional tools to run, such as the Windows Subsystem for Linux (WSL). | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
mrinfo |
Display information about a multicast router. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
msg |
Send a message to a user or session. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
muiunattend |
Manage unattended installs for Multilingual User Interface (MUI) packages. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
nbtstat |
Display protocol statistics and current TCP/IP connections using NetBIOS over TCP/IP. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
net1 |
A legacy version of the net command. |
Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
netcfg |
Install various network components. | Windows 8, Windows 10, Windows 11 |
netsh |
Configure and manage network settings and components. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
netdom |
Join a computer to a domain or manage domain trusts. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
nfsadmin |
Manage Network File System (NFS) server and client services. | Windows Server 2003, Windows Server 2008 |
nltest |
Perform network administrative tasks and verify trust relationships. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
ocsetup |
Install, list, or uninstall optional components in Windows. | Windows Vista, Windows 7 |
openfiles |
View and disconnect files and folders opened by network users. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
pagefileconfig |
Set up or display pagefile settings. | Windows XP, Windows Vista |
pathping |
Combine the ping and traceroute commands for network path information. |
Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
pause |
Pause the execution of a batch file until you press a key. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
perfmon |
Open the Performance Monitor utility. GUI only | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
pkgmgr |
Install, configure, or uninstall Windows packages. | Windows Vista, Windows 7 |
pnpunattend |
Install device drivers automatically. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
pnputil |
Manage various device drivers. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
popd |
Restore the previous value of the current directory saved by pushd. |
Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
print |
Print a text file. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
pushd |
Save the current directory and then change it. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
pwlauncher |
Turn on Windows To Go startup options. | Windows 8, Windows 10 |
qappsrv |
Display all Remote Desktop Session Host servers on the network. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
qprocess |
Show information about processes on a system. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
query |
Display information about servers, sessions, or processes. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
quser |
Display information about user sessions on a Remote Desktop Session Host server. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
qwinsta |
Display information about sessions on a Remote Desktop Session Host server. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
rasautou |
Manage automatic dialing for RAS connections. | Windows XP, Windows Vista, Windows 7 |
rasdial |
Connect to a remote network. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
rdpsign |
Digitally sign Remote Desktop Protocol (RDP) files. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
reagentc |
Set up the Windows Recovery Environment (WinRE). | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
recover |
Recover readable information from a damaged disk. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
reg |
Manage the Windows Registry. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
regedit |
Access the Windows Registry Editor. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
regini |
Modify the Windows Registry. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
register-cimprovider |
Register a Common Information Model (CIM) provider with Windows Management Instrumentation (WMI). | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
regsvr32 |
Register OLE controls and DLLs. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
relog |
Extract performance counter data from a log file. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
rem |
Add comments within batch files or scripts. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows 10, Windows 11 |
repair-bde |
Recover data from a damaged BitLocker-encrypted drive. | Windows 7, Windows 8, Windows 10, Windows 11 |
replace |
Replace files. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
reset |
Reset a session in a Remote Desktop environment. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
rmdir |
Remove a directory. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
rmtshare |
Manage shared resources remotely. | Windows 2000, Windows XP |
rpcinfo |
Show RPC information. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
rpcping |
Test remote procedure call (RPC) connectivity. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
runas |
Run a program as another user. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
rwinsta |
Reset the session subsystem hardware and software to default. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
sc |
Manage services from the command line. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
scconfig |
Configure service startup types and service recovery options. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
sdbinst |
Install and uninstall application compatibility databases. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
secedit |
Analyze and configure system security settings. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
setlocal |
Begin localization of environment changes in a batch file. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
setspn |
Manage Service Principal Names (SPN) for Active Directory. | Windows 2000, Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
setx |
Create or modify environment variables in the user or system environment. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
shadow |
Monitor and control a Remote Desktop session. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
shift |
Reposition replaceable parameters in a batch file. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
showmount |
Display mounted remote NFS file systems. | Windows Server 2003, Windows Server 2008 |
sigverif |
Verify the integrity of system files. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
subst |
Associate a path with a drive letter. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
sxstrace |
Trace issues with side-by-side assemblies. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
tcmsetup |
Set up Telephony Application Programming Interface (TAPI) clients. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
tpmvscmgr |
Manage Trusted Platform Module (TPM) virtual smart cards. | Windows 8, Windows 10, Windows 11 |
tracerpt |
Process logs or real-time trace data. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
tscon |
Connect a user to a session on a Remote Desktop Session Host server. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
tsdiscon |
Disconnect a Remote Desktop Services session. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
tskill |
Terminate a process by its process ID or name. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
typeperf |
Write performance data to the command window or a log file. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
tzutil |
Display or set the system time zone. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
umount |
Unmount network file systems. | Windows Server 2003, Windows Server 2008 |
unlodctr |
Unload Performance Monitor counter names and explain text for an extensible counter. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
vaultcmd |
Manage credentials in the Windows Vault. | Windows 7, Windows 8, Windows 10, Windows 11 |
verify |
Check if files are written correctly to a disk. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
vssadmin |
Set up Volume Shadow Copy services. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
w32tm |
Configure Windows Time service settings. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
waitfor |
Send or wait for a signal on a system. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
wbadmin |
Manage backup and restore operations. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
wecutil |
Manage subscriptions to Windows Event Collector (WEC). | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
wevtutil |
Manage Windows Event Log. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
winmgmt |
Manage the Windows Management Instrumentation (WMI) service. | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
winrm |
Manage Windows Remote Management. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
winrs |
Initiate remote commands on a remote computer. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
wmic |
Command-line interface for Windows Management Instrumentation (WMI). | Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
wsmanhttpconfig |
Configure Windows Remote Management (WinRM) and HTTP settings. | Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
xwizard |
Access the Windows Experience Wizard for performance and reliability testing. | Windows Vista, Windows 7, Windows 8 |
Deprecated and Obsolete CMD Commands
Over the years, many CMD commands have been replaced with modern alternatives, and some do not work in the latest Windows releases. However, older industrial machines, medical devices, ATMs, or even gaming enthusiasts may still operate machines that run on MS-DOS, Windows 95, and other obsolete systems.
The following table lists deprecated and obsolete CMD commands:
| Command | Description | Status | Compatibility |
|---|---|---|---|
append |
Control the path used to search for files in MS-DOS applications. | Deprecated | MS-DOS, Windows 95, Windows 98 |
at |
Schedule commands and programs to run on a computer at a specified time. | Deprecated and replaced by schtasks in later Windows versions. |
Windows XP, Windows Vista, Windows 7 |
atmadm |
Display information about asynchronous transfer mode (ATM) connections. | Deprecated | Windows 2000, Windows XP |
bitsadmin |
Manage Background Intelligent Transfer Service (BITS) jobs. | Deprecated and replaced by PowerShell cmdlets like Start-BitsTransfer. |
Windows XP, Windows Vista, Windows 7 |
bootcfg |
Configure boot file settings (boot.ini). | Deprecated and replaced by bcedit in modern systems. |
Windows XP, Windows Server 2003 |
break |
Enable or disable the CTRL+C feature to interrupt running scripts or commands. | Deprecated but retained for backward compatibility. | MS-DOS, Windows 95, Windows 98, Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows 11 |
cacls |
Modify access control lists (ACLs) of files. | Deprecated in favor of icacls. |
Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
cmdstp |
Stop a command processor started with the /k option. |
Deprecated | Windows XP |
command |
Start a new command interpreter instance in MS-DOS. | Obsolete. Replaced by cmd. |
MS-DOS, Windows 95, Windows 98 |
ctty |
Change the terminal device used to control MS-DOS. | Obsolete and no longer supported due to modern terminal management. | MS-DOS, Windows 95, Windows 98 |
dblspace |
Compress drives to increase disk space. | Obsolete | MS-DOS, Windows 95 |
debug |
Start the Debug tool to test and edit programs. | Deprecated | MS-DOS, Windows 95, Windows 98, Windows XP |
deltree |
Delete an entire directory, including subdirectories. | Deprecated | MS-DOS, Windows 95, Windows 98 |
diskcomp |
Compare the contents of two floppy disks. | Obsolete | MS-DOS, Windows 95, Windows 98 |
diskcopy |
Copy the contents of one floppy disk to another. | Obsolete | MS-DOS, Windows 95, Windows 98 |
dosshell |
Open the DOS Shell graphical interface. | Obsolete | MS-DOS, Windows 95 |
dosx |
Load the DOS Protected Mode Interface. | Obsolete | MS-DOS |
drvspace |
Compress drive to increase disk space. | Obsolete | MS-DOS, Windows 95 |
edit |
Start the MS-DOS text Editor. | Deprecated | MS-DOS, Windows 95, Windows 98, Windows XP |
edlin |
Create and edit text files in MS-DOS. | Obsolete | MS-DOS, Windows 95 |
emm386 |
Enable or disable EMM386 expanded memory support in MS-DOS. | Obsolete | MS-DOS, Windows 95 |
eventtriggers |
Configure event triggers to send notifications. | Deprecated and replaced by Task Scheduler. | Windows XP, Windows Vista |
exe2bin |
Convert .exe files to binary format. | Obsolete | MS-DOS |
extrac32 |
Extract CAB files (Windows Cabinet files). | Deprecated | Windows XP, Windows Vista |
extract |
Extract files from a compressed file. | Obsolete | Windows 95, Windows 98 |
fasthelp |
Help for MS-DOS commands. | Obsolete. The help command offers similar functionality. |
MS-DOS, Windows 95 |
fastopen |
Improve the performance of frequently used applications. | Obsolete | MS-DOS, Windows 95 |
fdisk |
Partition and configure hard drives. | Deprecated and replaced by diskpart. |
MS-DOS, Windows 95, Windows 98 |
forcedos |
Start a program in MS-DOS compatibility mode. | Obsolete | Windows 95, Windows 98 |
graphics |
Load a program that prints graphics screens. | Obsolete | MS-DOS, Windows 95 |
graftabl |
Display extended character sets in graphics mode. | Obsolete | MS-DOS, Windows 95, Windows 98 |
interlnk |
Connect two computers via serial or parallel ports. | Obsolete | MS-DOS |
intersvr |
Start the Interlnk server to share files over serial or parallel ports. | Obsolete | MS-DOS |
ipxroute |
Manage IPX routing tables for Novell networks. | Obsolete | Windows 95, Windows 98, Windows NT |
kb16 |
Use a specific keyboard layout for MS-DOS. | Deprecated | MS-DOS, Windows 95, Windows 98 |
keyb |
Configure the keyboard layout for MS-DOS. | Obsolete | MS-DOS, Windows 95, Windows 98 |
lh |
Load a program into upper memory. | Obsolete | MS-DOS, Windows 95 |
loadfix |
Load a program above the first 64K of memory to avoid conflicts. | Obsolete | MS-DOS, Windows 95 |
loadhigh |
Load a program into upper memory. | Obsolete | MS-DOS, Windows 95, Windows 98 |
lock |
Lock a drive to allow direct disk access. | Deprecated | MS-DOS, Windows 95, Windows 98 |
mem |
Display memory usage statistics. | Obsolete | MS-DOS, Windows 95 |
memmaker |
Optimize memory usage. | Obsolete due to modern automatic memory management. | MS-DOS |
msav |
Start Microsoft AntiVirus. | Obsolete | MS-DOS |
msbackup |
Create or restore backups in MS-DOS. | Obsolete | MS-DOS, Windows 95 |
mscdex |
CD-ROM access in MS-DOS. | Obsolete | MS-DOS, Windows 95 |
msd |
Start Microsoft Diagnostics. | Obsolete | MS-DOS, Windows 95 |
nlsfunc |
Load country-specific information for the MS-DOS program. | Obsolete | MS-DOS, Windows 95 |
ntbackup |
Back up and restore files. | Deprecated and replaced by Windows Backup and Restore. | Windows NT, Windows 2000, Windows XP |
ntsd |
Start the NT Symbolic Debugger. | Obsolete | Windows XP, Windows Server 2003 |
pentnt |
Detect floating-point division errors in Intel Pentium chips. | Obsolete | Windows 95, Windows 98, Windows NT |
power |
Turn power management on or off in MS-DOS. | Obsolete and replaced by the powercfg command on modern systems. |
MS-DOS, Windows 95 |
qbasic |
Start the QBasic programming environment. | Obsolete | MS-DOS, Windows 95, Windows 98 |
rcp |
Copy files to and from devices using the rshd daemon. | Obsolete and deprecated as it does not encrypt connections. | Windows XP, Windows 7, Windows 8 |
recimg |
Create a custom recovery image for Windows. | Deprecated | Windows 8 |
restore |
Restore files backed up with the backup command. | Obsolete | MS-DOS, Windows 95, Windows 98 |
rexec |
Execute commands on remote computers using the Rexec service. | Obsolete due to security concerns. | Windows XP, Windows 7, Windows 8 |
rsh |
Run commands on remote computers running the RSH (Remote Shell) service. | Obsolete due to security concerns. | Windows XP, Windows 7, Windows 8 |
rsm |
Manage removable storage media from the command line. | Deprecated | Windows XP, Windows Server 2003 |
scandisk |
Check and repair file system errors on a disk. | Deprecated and replaced with the chkdsk command. |
MS-DOS, Windows 95, Windows 98 |
scanreg |
Scan and back up the Windows Registry. | Obsolete | Windows 95, Windows 98, Windows Me |
setever |
Set the version number that MS-DOS reports to a program. | Obsolete | MS-DOS, Windows 95, Windows 98 |
share |
Install file-sharing and locking capabilities in MS-DOS. | Obsolete | MS-DOS, Windows 95 |
smartdrv |
Enable disk caching to improve performance in MS-DOS. | Obsolete | MS-DOS, Windows 95, Windows 98 |
sys |
Copy system files to a disk and make it bootable. | Obsolete | MS-DOS, Windows 95, Windows 98 |
tftp |
Transfer files to and from a remote computer using TFTP. | Deprecated due to security concerns. | Windows XP, Windows 7, Windows 8, Windows 10, Windows 11 |
tlntadmn |
Manage a Telnet server. | Deprecated | Windows 2000, Windows XP, Windows Server 2003 |
tsshutdn |
Restart or shut down a Terminal Services server. | Depreacted | Windows 2000, Windows Server 2003 |
undelete |
Recover deleted files in MS-DOS. | Obsolete | MS-DOS, Windows 95 |
unformat |
Recover a disk that was accidentally formatted. | Obsolete | MS-DOS, Windows 95 |
unlock |
Unlock a drive to allow direct disk access. | Deprecated | MS-DOS, Windows 95, Windows 98 |
vsafe |
Enable antivirus protection in MS-DOS. | Obsolete | MS-DOS |
winstat |
Display system statistics in MS-DOS. | Obsolete | MS-DOS |
Conclusion
After reading this comprehensive guide, you have a solid overview of nearly 300 Windows CMD commands and can perform a wide range of system tasks.
You can use CMD commands to set up cron jobs in Windows and automate repetitive everyday tasks.
Was this article helpful?
YesNo
