💾 Archived View for oakc.smol.pub › windows-command-prompt captured on 2023-12-28 at 15:01:28. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-11-04)

🚧 View Differences

-=-=-=-=-=-=-

<-- Back to Posts

Using the Windows Command Prompt

This post is adapted from a presentation I delivered in November 2021. It covers fairly basic usage of the Windows Command Prompt, so if you have just stumbled on this post while looking through the Smol net, the chances are you probably know all this already.

Background

Let's start with a bit of background of computing concepts you'll need to know to understand the Windows Command Prompt.

Directories

Directories are another name for folders as they’re essentially files that contain listings of the files in them. When a file is deleted, all that happens is that its entry in a directory is removed (like in a telephone directory). The "Folder" that isn't inside any subfolders on a drive is the "Root Directory"

Image of the C: drive root directory

Paths

Every file or folder/directory on the computer has a "Path", which is the address at which you find that file in the system. In Windows, this is made up of the Drive letter first, then a colon and a backslash, then each folder level that the file or folder is in separated by backslashes down to the file or folder you are specifying at the end.

Structure of a path of a directory

Each directory also contains two additional "Directory Entries": an entry for itself represented by a single dot (".") and one for its "parent" - that is the folder that contains it - represented by two dots (".."). The "Root Directory" of each drive doesn't contain the latter though as there is no directory to contain it.

Chart showing an example directory structure

A path can be specified in 3 ways:

Devices

Devices are special files that allow a command to refer to physical parts of the computer. They exist in every directory (folder) to keep them accessible and can have any extension (bit after the first dot in a filename). You can't use them as names of other files or folders (irrespective of the file extension). They are case insensitive, but it is traditional to refer to them in capital letters.

Here is a list of the devices and what they are used for:

While on the command-line, devices can be used as normal filenames, but in something like Microsoft Word they won't work.

Current Directory and Drive

The directory (folder) you're currently viewing the contents of or working inside is the "Current Directory" or "Working Directory". The drive of the current directory is the "Current Drive". Every drive has its own current directory so that when changing drives you return to working in the same directory as you were before.

Command Lines on Windows

There are two command lines available by default on Windows 10: The traditional "Command Prompt" (CMD), which has been on every version of Windows since 2000 (and some before then), uses short commands, is usually case insensitive, but is limited to not quite so advanced tasks; and the "Windows PowerShell", which can do a lot more than the Command Prompt, but is only available on more recent versions of Windows, uses long and complicated commands and is mostly case sensitive. In some cases, Windows 10 may offer access to the Unix-like "Bash" command-line, however this is not common. We will use the Command Prompt in this article for ease of use.

Commands

Some commands are built into the command prompt and are called "Internal Commands". These tend to be the simplest ones. Others are programs stored in system folders on your computer and are known as "External Commands". External commands can sometimes be case-sensitive, so it's worth checking the help on those commands (explained later). You can also run programs stored in the "current directory". Programs don't have to have their file extension specified. Programs with many different extensions can be run from the command prompt in this way, including ".exe", ".com" and ".bat".

Command Precedence

If a command is built into the Command Prompt then that will be the version that is run, even if there's a system version or one in the current directory - the command "cd" takes priority, for instance, over any external program called "cd.exe", for example (if you wanted to run "cd.exe", you'd have to specify the extension and/or the location). To force an external command, specify its extension. To force a program in the current directory regardless of its order within the precedence, specify it with its path (you can use a relative path like ".\cd.exe").

For external commands, the Command Prompt will look in a given order for an external command in the system folders (this order will be explained later). For any programs (including external commands) specified without an extension, the Command Prompt will check filenames of programs in another given order until it finds one that matches *this order will also be explained later).

Arguments

Anything that follows the name of the command is called the command's "arguments". These are terms separated by spaces, for example, in the command "cd MyFolder", there is one argument which is "MyFolder", but in the command "move MyFile MyFolder", there are two arguments: "MyFile" and "MyFolder". If you need to include a space within an argument, you can enclose the argument with speechmarks, for example:

move "My File" MyFolder

This command has two arguments: "My File" and "MyFolder".

If for some reason, you need to include a speechmark within an argument, you can precede the speechmark with a caret ("^"), which tells the command prompt to interpret the speechmark literally rather than as a marker for the arguments:

ACommand "Some text needing a speechmark: ^" ."

The caret acts here as an "escape character". Note that if for some reason you need to specify a literal caret within an argument, you can use two carets ("^^") to apply the "escape" to the caret itself:

ACommand "Some text needing a caret: ^^ ."

Using Wildcards

In many commands that require a file as an argument, you can instead give a "pattern" that "matches" a selection of multiple files. This pattern is made from giving the known characters in a filename and putting special characters, known as "Wildcards", in the places with unknown characters.

There are two different wildcards: "?" (a question mark) and "*" (an asterisk). The question mark ("?") refers to exactly one unknown character. Therefore "H?llo" would match "Hello", "Hullo", "Hjllo", "H3llo", "H.llo", "H llo", etc., but not "Hllo" or "Heallo" as it has to replace exactly one character. However, if another exact number of characters needs to be matched, multiple question marks ("?") can be specified; so "H???o" would match both "Hello" and "Hoppo" etc..

If there is a need to match an unknown number of unknown characters, this is where the asterisk ("*") comes into use. The asterisk ("*") matches zero or more (basically any number of) unknown characters, so "H*" would match anything beginning with "H" ("Hello", "Hot Potato", "Hullaballoo", etc.) but also just "H". For a more real-world example, "IMG*.png" matches any PNG image whose filename begins with the letters "IMG" (including "IMG.png" itself).

Commands Help

You can get help on most commands by using the argument "/?". Some commands will also give you help if you type "help command" where "command" is the command name, however this is only a smaller subset and provides no more information than the "/?" method.

Some external commands have other methods of specifying a request for help - for those, it's often easier to look up their specific documentation online.

Simple Command Examples

cd

The "cd" command changes the current directory to the one specified in its argument; for example:

cd DirectoryPath

This changes the current directory to "DirectoryPath". This path could be an absolute path, like "C:\Windows", a directory in the current directory or another type of relative path. The command:

cd ..

changes the current directory to the parent of the current directory (unless the current directory is already the root directory of the drive, in which case it has no effect). If you change the current directory to another on a different drive, command prompt will simply change the current directory for that drive, rather than the current directory for the current drive. For instance, if the current drive is "C:" and the current directory of that drive is "C:\Windows", typing "cd D:\Folder" will appear to have no effect, but will actually change the current directory of the "D:" drive to that directory: the "C:" drive's current directory will remain as "C:\Windows".

If you type "cd" with no arguments, cmd will respond with the path of the current directory of the current drive.

C:

"C:" changes the current drive to the "C:" drive. Every drive in Windows has a letter and any that are currently in use can be changed to by typing their letter followed by a colon. This means that to change the current drive and current directory takes two command but the two commands can be written in either order.

dir

The "dir" command lists the contents of the current directory or, if given as an argument, a specified directory, for example, "dir C:\Windows" lists all the files in the Windows directory in the root of the "C:" drive. If the argument is instead a filename, it will list that file and a little information about it. However, it will also accept a pattern as a filename, meaning it can list all the files corresponding to that pattern, for example "dir *.txt" lists all the text files in the current directory.

date & time

The "date" command lets you display or set the current date. If you just want to display the current date, use the "/T" argument (that is, the command "date /T"), otherwise you will be prompted for a new date. There is also the command "time", which sets or displays the current time and works in the same way.

ren

The "ren" command renames a file or a directory to a new name. The current name is given as the first argument and the new name as the second, for example:

ren OldFile NewFile

Patterns can be used to change certain parts of a filename, for example:

ren Old????.txt New????.txt

This will change any file in the current directory called "OldFile.txt" to "NewFile.txt", but also any other file that starts with "Old" then has 4 characters, then ends with ".txt" (such as "OldPage.txt") to start with "New", then the original 4 characters, then the ".txt" (such as "NewPage.txt" for the aforementioned filename).

type

The "type" command writes out the contents of a file specified as an argument (that is, a command such as "type textfile.txt") to the command prompt screen. This is only worth doing with files that are basically unformatted text (such as those ending in ".txt") as otherwise the contents will be reinterpretted as if they were unformatted text and the command prompt screen will be filled with what looks like nonsense characters.

del

The "del" command deletes whatever file is given as an argument; for example, "del caviar.txt" deletes the file "caviar.txt" from the current directory. The deleted file will be permanently deleted rather than being moved to the Windows Recycle Bin, so be careful with this command. The "del" command can be used with a pattern as an argument, for example "del *.png" to delete all the PNG images in the current directory, however this can be even more dangerous as you won't necessarily know in advance all the files it will delete. Therefore, this command should be used with high levels of care!

md

The "md" command makes a new (empty) directory with the name given in the argument. For example, to make a new directory called "MyFiles" in the current directory, you would type:

md MyFiles

However, to make a new directory called "MyTextFiles" inside your newly created "MyFiles" directory, you would type:

md MyFiles\MyTextFiles

This gives the new directory name as a relative path to the "md" command, which creates the last directory in the path. Note that you cannot use this method to create both directories at once as all the preceding directories in the path have to exist already.

Once you have created a directory, you can change into it with "cd" in the normal way.

rd

The "del" command only deletes files, not directories. To delete a directory, you can use the "rd" command with the directory as an argument, though for safety the directory must have already had its contents deleted:

rd EmptyDirectory

You can delete a directory and all its contents without first emptying it by specifying the "/s" argument:

rd /s ADirectory

This is, however, fairly dangerous as a mistyped directory name may result in the deleting of files you wanted to keep.

Directories and files deleted with "rd" are permanently deleted so do not appear in the Recycle Bin. Therefore, you should be very careful with this command.

copy

The "copy" command copies a single file, or a set of files that match a pattern, from one place to another. Copies can also be made within the same directory if a new filename is specified:

copy ATextFile.txt NewTextFile.txt

The above command makes a copy of the file "ATextFile.txt" within the same directory and calls it "NewTextFile.txt". To copy it instead into a subdirectory called "SubDirectory" with the new name, you would instead write:

copy ATextFile.txt SubDirectory\NewTextFile.txt

To copy the file into the subdirectory but keeping the same name, you can instead type:

copy ATextFile.txt Subdirectory\

You can copy files in bulk if they match a given pattern. To copy all the PNG images in the current directory to the subdirectory "SubDirectory", write:

copy *.png SubDirectory\

Similarly, to copy every file in the subdirectory "SubDirectory" to the current directory, you would type:

copy SubDirectory\* .\

An important thing to note is that the "copy" command only copies files, not directories. To copy an entire directory, you will need to use the "xcopy" command.

The "copy" command can also be used to copy from devices, such as to create a blank file by copying from the NUL device:

copy NUL BlankFile.txt

The size of "BlankFile.txt" will be 0 Bytes.

Similarly, you can write a file to the screen, similarly to using the "type" command, by copying it to the CON device:

copy AFile.txt CON

echo

The "echo" command does two jobs.

When followed by the word "on" or the word "off", the "echo" command controls the "echoing" of commands back to the screen (so you can see what command is being executed). Usually, you want this on, but if you are automating a series of commands (see later in the document), you may wish to turn echoing off to hide some commands. When "echo" is not followed by anything, it reports back whether command echoing is on or off.

If the "echo" command is followed by any other text, it will simply write that text to the screen, e.g.:

echo Hello Everyone!

The "echo" command doesn't need speechmarks for including spaces (for compatibility reasons) and, indeed, will treat them as part of the text to be outputted if it encounters them.

To write a blank line to the screen, you can follow the "echo" command immediately with a full-stop:

echo.

color

The "color" command sets the foreground and background colours of the text displayed on the command prompt. Note the American spelling of "color" - there isn't a command for "colour". The foreground and background colours are written as two hexadecimal digits - each is specified as ome of 0-9, A-F for the various colours. The background colour is specified first, followed by the foreground colour. For example:

color 0E

Sets the foreground colour to yellow ("E") and the background colour to black ("0"). To get a list of the colours and their values, use the help argument to the command:

color /?

move

The "move" command moves a file (or a selection of files via a pattern) from one directory to another in a similar way to the "copy" command.

For example, to move a single file called "ATextFile.txt" into a directory called "AnotherDirectory" you would type:

move ATextFile.txt AnotherDirectory

To move all Excel files from the current directory to the directory above, you would type:

move *.xlsx ..

Unlike the copy command, the move command can be used with directories, for example, to move "ADirectory" into "AnotherDirectory", you would type:

move ADirectory AnotherDirectory\

explorer

The "explorer" command opens the Windows File Explorer - with no arguments it's like just clicking on the file explorer in the taskbar, however if you provide a path as an argument it opens the file explorter to show that path, for example:

explorer C:\Users\

exit

Use the "exit" command to exit the command prompt when you are finished.

More Advanced Topics - Keys

In the modern Windows Command Prompt, there are a selection of key combinations that help with the entering of commands:

More Advanced Topics - Environment Variables

Every session of the Command Prompt (indeed, every session of any program) is assigned a list of "Environment Variables". These are changeable variables stored in Windows that describe the "environment" in which commands and programs will be run. Windows has a default set of Environment Variables that are copied for use when Command Prompt starts. These can be changed for the current session within the Command Prompt itself using the "set" command, however they will revert back to their original value for each new session of Command Prompt. To change them for every session of every program, you can adjust them in the Windows Settings.

Each variable can be used inside arguments by writing its name within per-cent symbols, e.g. "%VARIABLE%", though some single-character variables can be written without a second per-cent symbol (e.g. "%1"). This means that if you want to use a per-cent symbol ("%") normally, you must specify two consecutively ("%%") to let the command prompt know you aren't referring to an environment variable.

The %CD% Environment Variable

An example of an environment variable is "%CD%". This is set automatically with the current directory every time you change the current directory (with the "cd" command) within Command Prompt. This means you can type:

echo %CD%

to see the current directory if it is not shown on the prompt. This variable can also be useful for passing the current directory to programs that don't take it into account normally and merely rely on arguments, like the Windows File Explorer: to show the current directory in the Windows file explorer, you would type:

explorer %CD%

The %PATH% Environment Variable

The "%PATH%" environment variable is how the Command Prompt knows where to find programs used as external commands. It contains a series of directory paths separated by semicolons, e.g.:

C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;

(In practice, most "%PATH%" environment variables are a lot longer than this).

Each directory in the "%PATH%" environment variable is searched in turn for programs with the name of the command that was used and the first one found is then run. You can see its contents with:

echo %PATH%

The %PATHEXT% Environment Variable

If there are two programs with the same name (without extension) in the same directory, Command Prompt needs to know which to run when just given the program name as a command. The "%PATHEXT%" environment variable governs this as it contains a list of executable file extensions separated by semicolons. Each file extension is looked for in turn, with the first found being run. Usually the order is something like:

.COM;.EXE;.BAT;.CMD

So, in this case, ".com" and ".exe" take priority over others in the list. You can see the contents of the "%PATHEXT%" environment variable with:

echo %PATHEXT%

The %ERRORLEVEL% Environment Variable

When a command finishes running, it often changes the value of the "%ERRORLEVEL%" Environment Variable. "%ERRORLEVEL%" is a number: A value of "0" usually means the command worked, with any other number being an error that can be looked up in a manual somewhere. Some commands/programs use it to output other numeric information for use in automated sequences of commands (e.g. "batch files"). Some commands (like "echo") don't change the value of the "%ERRORLEVEL%" so that they can be used for testing what the last program did without affecting the next. Note that a mistyped command gives an "%ERRORLEVEL%" value of 9009. Some commands (like "if", which will be covered later) can be made to do different things depending on the last value of the "%ERRORLEVEL%". You can see the contents of the "%ERRORLEVEL%" environment variable with:

echo %ERRORLEVEL%

More Advanced Commands

if

The "if" command is used to execute another command only if a given condition is met. The syntax of the if command is "if condition command", with various conditions available, best explained through examples:

if exist textfile.txt type textfile.txt

The above command writes the contents of "textfile.txt" to the screen only if it exists, using the if command to avoid giving an error if it doesn't.

if ERRORLEVEL 3 echo Error of three or above!

The "if ERRORLEVEL" command above will trigger the message to be written to the screen if the errorlevel environment variable is at least the specified value (3 in this case). Since a nonexistent command causes an errorlevel of 9009, this will trigger the above.

if "%ERRORLEVEL%"=="2" echo Error Two!

By using the errorlevel environment variable directly, the above command compares the two strings of text and triggers showing the message to the screen if they are both equal. It is important to use the speechmarks around both values to ensure there is always something to compare.

if not "%ERRORLEVEL%"=="0" echo An error occurred!

The presence of "not" in the above if command causes the command to be triggered if the condition is not true, so in this case if the errorlevel environment variable is anything but 0. This can also be useful for the following type of command:

if not exist .\ADirectory md ADirectory

The above command creates a directory called "ADirectory" only if it doesn't already exist in the current directory.

It is also possible to specify an action to take if the condition is not met as part of the same if command as checking whether it is met, using the syntax "if condition (command) else command", for example:

if exist textfile.txt (type textfile.txt) else echo File missing!

The above command will write the file textfile.txt to the screen if it exists in the current directory and tell the user it's missing if it doesn't exist.

For more information on the if command, use the "if /?" command in command-prompt.

xcopy

The "xcopy" command copies a directory and it's contents rather than just a single file or group of files via a pattern like the "copy" command does. For example:

xcopy NameOfDirectory F:\

The above command copies the directory "NameOfDirectory" and any files it contains to the root directory of a (probably external) drive called "F:". By default, xcopy ignores subdirectories. To get it to include them, use "/e" as the last argument, for example:

xcopy NameOfDirectory F:\ /e

Note that if you use "F:" instead of "F:\" in the above example (as in the below example), the specified directory ("NameOfDirectory") and contents will be copied to the "F:" drive's current directory (whatever the current directory was when you last used that drive), which might not be the root directory! (This is the same with the "copy" and "move" commands).

xcopy NameOfDirectory F: /e

For more information on the xcopy command, use the command "xcopy /?".

shutdown

The "shutdown" command shuts down or restarts the computer (be very careful with this). To shut down the computer, you must specify the "-s" argument and to restart the "-r" argument. You must also specify an time (number of seconds) until the shutdown takes place:

shutdown -s -t 0

The above command shuts down the computer immediately, while the following command will wait 30 seconds then restart the computer:

shutdown -r -t 30

When a number of seconds greater than 0 is specified for the time, a message will appear onscreen warning of the impending shutdown. If there is still time before a shutdown is due to take place, you can cancel it with the command:

shutdown -a

choice

The "choice" command asks for a choice of letters to represent options and changes the value of the errorlevel environment variable to indicate the choice made. This is useful for adding interactivity to an automated series of instructions (a batch file).

Using "choice" with no arguments asks:

[Y,N]?

(for "yes" and "no" respectively). If you type "Y", the value of the errorlevel environment variable is set to 1, if "N" it is set to 2, if you type anything else the command will refuse to accept the inputted keypress and the command won't end.

To specify a custom series of choices, you would use the "/C" argument:

choice /C YNC

The above command asks:

[Y,N,C]?

(for "yes", "no" or "cancel" respectively), with the option "C" giving an errorlevel value of 3. Any letters can be entered in the argument as choices, with errorlevel values assigned from left to right, beginning at 1.

Remember that to see the errorlevel value, you can use the command:

echo %ERRORLEVEL%

pause

The "pause" command waits for a keypress while displaying the following message on the screen:

Press any key to continue . . .

It is designed to be used in an automated sequence of commands (a batch file) to stop the sequence temporarily. This can be used to ensure that the person running the script has time to see the result of a command before it is overwritten onscreen.

Image of command-prompt running the "pause" command.

Other useful commands

wmic logicaldisk get name

help

cls

tree

set

set MyVariable=23

Batch Files

A batch file is an automated sequence of commands forming a script program. To create a batch file in Windows, type the commands into Notepad and save the file with the ".bat" file extension (instead of the default ".txt" file extension - e.g. save as "MyBatchFile.bat"). The commands will be executed in order unless the "goto" command is used (which we will discuss later). When execution of the commands in the batch file gets to the end of the sequence of commands, the batch file program will end and, if the batch file was run through double-clicking it, with no further task to perform the command-prompt window will exit.

In a batch file, unless you want to know every command that is being executed rather than just the results of the commands, you usually don't want the "command echoing" on, so your first command is usually a variation of "echo off". You can precede any command with an at sign ("@") to turn echoing off for just that command and since echoing for the batch file otherwise will not turn off until after the command-prompt has encountered the "echo off" command, your first command is thus usually:

@echo off

Commands that only work within batch files

:LabelName

The above command defines a label called "LabelName" the specifies an exact point within the sequence of commands that can be "jumped" to with the "goto" command. Any text can be used for a label name as long as it's all one word and starts with a colon (":"). A label must be the only command on its line of text.

goto LabelName

The "goto" command "jumps" execution of the commands in the sequence to the specified point in the batch file. It uses as an argument a label name defined somewhere else in the batch file - the above command jumps execution to the label defined by the ":LabelName" command. The "goto" command is commonluy used with the "if" command to jump execution based upon a condition.

A (Very) Simple Example Batch File

Type the following into Notepad and save as "Hello.bat":

@echo off
echo Hello
pause

Then run the batch file by double-clicking it.

Here, the "pause" command is used so that you can see the message before the window disappears.

A Simple Example Batch File

Type the following into Notepad and save it as "Dinner.bat"

@echo off
echo Do you want dinner yet?
choice
if ERRORLEVEL 2 goto No
echo OK, I will serve it in a minute.
goto Exit
:No
echo I see that you do not.
:Exit
pause

You can then run the batch file by double-clicking it.

Here, the "if" command responds to the errorlevel set by the "choice" command and uses the "goto" command to jump to a command to handle that choice.

Conclusion

This was a simple run through of using the command-prompt. For more information on any of the commands, you can usually type the command name followed by the argument "/?" into the command-prompt (some external commands imported from other systems may use "-?", "-h" or "--help" as their argument for help).

Addendum

There was, for the original presentation, another section demonstrating how to use an external command, for which a simple command-line program was written. This can be found on a separate page:

"Chooser" program for the presentation.