Windows 10 comes with a large collection of command-line disk management tools that enable you to check disks or partitions for errors, as well as defragment, format, partition, and convert disks. Table B.1 lists the disk management tools you can use with Windows 10.
If you need a refresher on accessing and using the command line, see Chapter 30, “Command-Line and Automation Tools.”
note
In this section, we use the word volume to refer to any disk, partition, or mount point.
The next three sections give you more detailed coverage of the CHKDSK
, CHKNTFS
, and DEFRAG
tools.
Tool |
Description |
|
Checks a specified volume for errors. |
|
Configures automatic disk checking. |
|
Converts a specified volume to a different file system. |
|
Defragments a specified volume. |
|
Compares the contents of two floppy disks. (This tool does not compare hard disks or other types of removable media, such as memory cards.) |
|
Copies the contents of one floppy disk to another. (This tool does not copy hard disks or other types of removable media, such as memory cards.) |
|
Enables you to list, create, select, delete, and extend disk partitions. |
|
Extracts one or more files from a compressed file, such as a.cab file found on some installation discs. |
|
Formats the specified volume. |
|
Performs a number of file system tasks. |
|
Changes or deletes the name of a specified volume. |
|
Creates, displays, or deletes a mount point. |
|
Displays the name and serial number of a specified volume. |
CHKDSK
: Checking for Hard Disk ErrorsIn Chapter 25, “Managing Hard Disks and Storage Spaces,” you learned how to use the Check Disk utility to check a hard disk for errors. Check Disk also comes with a command-line version called CHKDSK
that you can run in a Command Prompt window.
Here’s the syntax for CHKDSK
:
CHKDSK [volume [filename]] [/F] [/V] [/R] [/B] [/X] [/I] [/C] [/L:[size]] [/scan] [/forceofflinefix] [/perf] [/spotfix] [/freeorphanedchains] [/markclean] [/offlinescanandfix] [/sdcleanup]
For example, to run a read-only check—that is, a check that doesn’t repair errors—on drive C, you enter the following command:
chkdsk c:
note
To run the CHKDSK
utility on the system drive, you must use an administrator Command Prompt session. Press Windows Logo+X (or right-click the Start button), click Command Prompt (Admin), and then enter your User Account Control credentials.
Note that when you use the /F
switch to fix errors, CHKDSK
must lock the volume to prevent running processes from using the volume during the check. If you use the /F
switch on the %SystemDrive%
, which is the drive where Windows 10 is installed (usually drive C:), CHKDSK
can’t lock the drive, and you see the following message:
Cannot lock current drive. Chkdsk cannot run because the volume is in use by another process. Would you like to schedule this volume to be checked the next time the system restarts? (Y/N)
If you press Y and Enter, CHKDSK
schedules a check for drive C: to run the next time you reboot Windows 10.
CHKNTFS
: Scheduling Automatic Disk ChecksYou saw in the preceding section that CHKDSK
prompts you to schedule an automatic disk check during the next reboot if you run CHKDSK
/F
on the system drive (usually drive C: in Windows 10).
If you press Y and Enter at these prompts, CHKDSK
adds the AUTOCHK
utility to the following Registry setting:
HKLMSYSTEMCurrentControlSetControlSession ManagerBootExecute
This setting specifies the programs that Windows 10 should run at boot time when the Session Manager is loading. AUTOCHK
is the automatic version of CHKDSK
that runs at system startup.
Windows 10 also comes with a command-line tool named CHKNTFS
that enables you to cancel pending automatic disk checks, schedule boot-time disk checks without using CHKDSK
, and set the time that AUTOCHK
counts down before running the automatic disk checks.
Here’s the syntax for CHKNTFS
:
CHKNTFS [volume ][/C volume:] [/X volume:] [/D] [/T:[time]]
|
Specifies a drive letter (followed by a colon) or mount point. |
|
Tells CHKNTFS to schedule an automatic startup disk check for the specified volume. You can specify multiple volumes (separated by spaces). |
|
Tells CHKNTFS to exclude the specified volume from an automatic startup disk check. You can specify multiple volumes (separated by spaces). |
|
Tells CHKNTFS to exclude all volumes from an automatic startup disk check. |
|
Specifies the time that AUTOCHK counts down before starting the automatic disk checks. |
When you run CHKNTFS
with just a volume name, you see one of the following:
If the volume is not scheduled for a startup disk check, you see the volume’s file system:
The type of the file system is NTFS.
If the volume is scheduled for a startup disk check, you see the following message:
Chkdsk has been scheduled manually to run on next reboot.
If Windows 10’s Storage Manager has detected an error on the volume, it marks the volume as dirty, so in this case, you see the following message (using drive C: as an example):
C: is dirty. You may use the /C option to schedule chkdsk for this drive.
note
To manually mark a volume as dirty, use the FSUTIL DIRTY SET
volume
command, where volume
is the drive you want to work with. For example, the following command marks drive C: as dirty:
fsutil dirty set c:
If you’re not sure whether a drive is dirty, either run CHKNTFS
volume
or run FSUTIL DIRTY QUERY
volume
, as in this example:
fsutil dirty query c:
Note, however, that FSUTIL
doesn’t give you any way to unmark a drive as dirty.
This last message is confusing because Windows 10 always performs an automatic startup disk check of any volume that’s marked as dirty. What you can do with CHKNTFS
is bypass the automatic startup disk check of any volume that is marked as dirty. To do that, run CHKNTFS
with the /X
switch, as in this example:
chkntfs /x c:
If a volume isn’t already marked as dirty, you can force CHKDSK
to check a volume at startup by running CHKNTFS
with the /C
switch. For example, the following command sets up an automatic start check for the D: drive:
chkntfs /c d:
Note that the /C
switch is cumulative, meaning that if you run it multiple times and specify a different volume each time, CHKNTFS
adds each new volume to the list of volumes to check at startup. Instead of running multiple commands, however, you can specify multiple volumes in a single command, like so:
chkntfs /c c: d:
note
To run the CHKNTFS
utility on the system drive, you must use an administrator Command Prompt session. Press Windows Logo+X (or right-click the Start button), click Command Prompt (Admin), and then enter your User Account Control credentials.
To learn how to add Command Prompt (Admin) to the Start Menu’s shortcut menu, see “Adding Command Prompt to the Shortcut Menu,” p. 129.
If you know a volume has been scheduled for a startup check but you want to cancel that check, run CHKNTFS
with the /X switch, as in this example:
chkntfs /x d:
You can also specify multiple volumes if needed:
chkntfs /x c: d:
If you know that multiple volumes are scheduled for automatic startup checks, you can cancel all the checks by running CHKNTFS
with the /D
switch:
chkntfs /d
If you’ve scheduled a startup check for one or more volumes, or if a volume is marked as dirty, the next time you reboot Windows 10, you see a message similar to the following (which uses drive C: as an example):
Checking file system on C: The type of the file system is NTFS. Volume label is SYS. One of your disks needs to be checked for consistency. You may cancel the disk check, but it is strongly recommended that you continue. To skip disk checking, press any key within 10 second(s).
The number of seconds in the last line counts down to 0. If you press a key before the countdown ends, Windows 10 skips the disk check; otherwise, it continues with CHKDSK
.
caution
Pressing any key to skip the disk check usually works only with wired keyboards. On most wireless keyboards, pressing a key has no effect.
You can change the initial countdown value by running CHKNTFS
with the /T
switch, followed by the number of seconds you want to use for the countdown. For example, the following command sets the countdown to 30 seconds:
chkntfs /t:30
Note that if you run the command CHKNTFS /T
(that is, you don’t specify a countdown value), CHKNTFS
returns the current countdown value.
DEFRAG
: Defragmenting the System DriveIn Chapter 25, you learned how to defragment a volume using Windows 10’s Optimize Drives program. If you want to schedule a defragment or perform this chore from a batch file, you have to use the DEFRAG
command-line tool. Here’s the syntax:
DEFRAG disks [task(s)] [/A] [/C] [/D] [/E] [/G] [/H] [/I n
] [/K] [/L] [/M] [/O] [/T] [/U]
[/V] [/X]
|
Specifies the drive letter (followed by a colon) of each disk you want to defragment. (Separate multiple drives with a space.) |
|
As this book went to press, Microsoft had not provided information on this new parameter. |
|
Tells DEFRAG only to analyze the disk. |
Tells DEFRAG to defragment all the system’s drives. |
|
|
Tells DEFRAG to run a traditional optimization (that is, one that does not include the task(s) parameter; this is the default switch, meaning that this is the type of optimization that DEFRAG runs if you don’t specify switches). |
|
Tells DEFRAG to defragment all the system’s drives except those specified with the disks parameter. |
|
Optimize the drive's storage tiers. |
|
Runs DEFRAG with a higher program priority for better performance. |
|
Tells DEFRAG to run tier optimization for at most n seconds. |
|
Runs DEFRAG as a slab consolidation, which, if you use a storage pool on a thinly provisioned volume, moves data from lightly used allocation units—called slabs—to more heavily used slabs, thus enabling the lightly used (and now empty) slabs to be returned to the storage pool. |
|
Runs DEFRAG as a retrim operation on a solid-state drive (SSD), which marks all sectors formerly used by deleted files as not being currently in use. |
|
Tells DEFRAG to defragment all the specified drives at the same time (in parallel). |
|
Tells DEFRAG to analyze each type of media being used during the operation and to modify the type of optimization based on each media type. |
|
Tells DEFRAG to show the progress of an already running defrag. |
|
Tells DEFRAG to show the progress of the defrag. |
|
Runs DEFRAG in verbose mode, which displays both the analysis report and the defragmentation report. |
|
Consolidates the free space on the volume. |
note
To run the DEFRAG
utility, you must use an administrator Command Prompt session. Press Windows Logo+X (or right-click the Start button), click Command Prompt (Admin), and then enter your User Account Control credentials.
For example, to get an analysis report of the fragmentation of drive C:, enter the following command:
defrag c: /a
If the volume isn’t too fragmented, you see a report similar to this:
Post Defragmentation Report: Volume Information: Volume size = 116.49 GB Free space = 106.89 GB Total fragmented space = 1% Largest free space size = 56.49 GB Note: File fragments larger than 64MB are not included in the fragmentation statistics. You do not need to defragment this volume.
However, if the drive is quite fragmented, you see a report similar to the following:
Post Defragmentation Report: Volume Information: Volume size = 397.12 GB Free space = 198.32 GB Total fragmented space = 9% Largest free space size = 158.43 GB Note: File fragments larger than 64MB are not included in the fragmentation statistics.
It is recommended that you defragment this volume.
If you try to defragment a volume that is running low on disk space, DEFRAG
displays the following message:
Volume DATA has only 9% free space available for use by Disk Defragmenter. To run effectively, Disk Defragmenter requires at least 15% usable free space. There is not enough disk space to properly complete the operation. Delete some unneeded files on your hard disk, and then try again.
File Explorer is the GUI tool of choice for most file and folder operations. However, Windows 10 comes with an impressive collection of command-line file and folder tools that let you perform all the standard operations, such as renaming, copying, moving, and deleting, as well as more interesting chores, such as changing file attributes and comparing the contents of two files. Table B.2 lists the file and folder management tools you can use with Windows 10.
The next few sections take a closer look at a half dozen of these tools: ATTRIB
, FIND
, REN
, REPLACE
, SORT
, and XCOPY
.
Before getting to the tools, we should mention that most of the file and folder management tools work with the standard wildcard characters: ?
and *
. In a file or folder specification, you use ?
to substitute for a single character, and you use *
to substitute for multiple characters. Here are some examples:
File Specification |
Matches |
Budget201?.xlsx |
Budget2017.xlsx, Budget2018.xlsx, and so on |
Memo.doc? |
Memo.doc, Memo.docx, Memo.docm, and so on |
*.txt |
ReadMe.txt, log.txt, to-do.txt, and so on |
*201?.pptx |
Report2016.pptx, Budget2017.pptx, Conference2018.pptx, and so on |
*.* |
Every file |
ATTRIB
: Modifying File and Folder AttributesA file’s attributes are special codes that indicate the status of the file. There are nine attributes you can work with:
Archive—When this attribute is turned on, it means the file has been modified since it was last backed up.
Hidden—When this attribute is turned on, it means the file doesn’t show up in a DIR
listing and isn’t included when you run most command-line tools. For example, if you run DEL *.*
in a folder, Windows 10 deletes all the files in that folder, except the hidden files.
Integrity—When this attribute is set, it means the volume is configured with integrity, where data is stored in such a way that it is protected from certain types of file errors. Although technically available in Windows 10, this attribute works only with Windows 10 Server volumes formatted with the Resilient File System (ReFS) file system.
Offline—When this attribute is turned on, it indicates that the file is not currently available because its data has been moved to offline storage.
No scrub—When this attribute is set, the file is skipped by the scrubber, which is a background service that identifies and (if possible) fixes certain types of file errors. Again, this attribute works only with Windows 10 Server volumes formatted with the ReFS file system.
Not content indexed—When this attribute is set, the file’s contents will not be indexed for searching.
Read-only—When this attribute is turned on, it means the file can’t be modified or erased.
Pinned—When this attribute is set, it indicates the file is an NTFS sparse file. This tells Windows to allocate on disk only the file's nonzero (meaningful) data.
System—When this attribute is turned on, it means the file is an operating system file (that is, a file that was installed with Windows 10).
The ATTRIB
command lets you turn these attributes on or off. Here’s the syntax:
ATTRIB [+A | -A] [+H | -H] [+I | -I] [+O | -O] [+P | -P] [+R | -R] [+S | -S] [+U | -U] [+V | -V] [+X | -X] filename [/S [/D] [/L]]
|
Sets the archive attribute. |
|
Clears the archive attribute. |
|
Sets the hidden attribute. |
|
Clears the hidden attribute. |
|
Sets the content not indexed attribute. |
|
Clears the content not indexed attribute. |
|
Sets the offline attribute. |
Clears the offline attribute. |
|
|
Sets the pinned attribute. |
|
Clears the pinned attribute. |
|
Sets the read-only attribute. |
|
Clears the read-only attribute. |
|
Sets the system attribute. |
|
Clears the system attribute. |
|
Sets the integrity attribute. |
|
Clears the integrity attribute. |
|
Sets the integrity attribute. |
|
Clears the integrity attribute. |
|
Sets the no scrub attribute. |
|
Clears the no scrub attribute. |
|
Specifies the file or files you want to work with. |
|
Applies the attribute change to the matching files in the current folder and all of its subfolders. |
|
Applies the attribute change only to the current folder’s subfolders. You must use this switch with /S. |
|
Applies the command to a symbolic link (that is, an NTFS file system object that points to another file system object, which is called the target) rather than to the target of the symbolic link. |
For example, if you want to hide all the .docx
files in the current directory, use the following command:
attrib +h *.docx
As another example, if you’ve ever tried to delete or edit a file and received the message “Access denied,” the file is likely read-only. You can turn off the read-only attribute by running ATTRIB
with the -R
switch, as in this example:
attrib -r readonly.txt
note
If you want to check out a file’s attributes, use the DIR
command’s /A
switch. Use /AA
to see files with their archive attribute set; /AH
for hidden files; /AI
for not content indexed files; /AR
for read-only files; /AS
for system files; and /AX
for integrity files.
You can also use ATTRIB
for protecting important or sensitive files. When you hide a file, it doesn’t show up in a listing produced by the DIR
command. Out of sight is out of mind, so someone taking a casual glance at your files won’t see the hidden ones and, therefore, won’t be tempted to display or erase them.
Although a hidden file is invisible, it’s not totally safe. Someone who knows the name of the file can attempt to modify the file by opening it with the appropriate program. As an added measure of safety, you can set the file’s read-only attribute. When you do this, the file can’t be modified. You can set both attributes by using a single command:
attrib +h +r payroll.xlsx
FIND
: Locating a Text String in a FileYou use the FIND command to search for a string inside a file. Here’s the syntax:
FIND [/C] [/I] [/N] [/V] [/OFF[LINE]] "string" filename
|
Displays the number of times that |
|
Performs a search that is not case sensitive. |
|
Displays each match of |
|
Displays the lines in |
|
Tells |
|
Specifies the string you want to search for. |
|
Specifies the file you want to search in. (Note that you can’t use wildcards with the FIND command.) If the filename contains one or more spaces, surround it with double quotation marks. |
For example, to find the string Xbox
in a file named WishList.txt
, you use the following command:
find "Xbox" WishList.txt
note
The FIND
command doesn’t work with the XML-based file formats used in Microsoft Office 2007 and later. However, it works fine with most documents created in earlier versions of Office.
If the string you want to find contains double quotation marks, you need to place two quotation marks in the search string. For example, to find the phrase Dave “The Hammer” Schultz in the file players.doc
, use the following command:
find "Dave ""The Hammer"" Schultz" players.doc
tip
The FIND
command doesn’t accept wildcard characters in the filename parameter. That’s too bad because it’s often useful to search multiple files for a string. Fortunately, you can work around this limitation by using a FOR loop where the command you run on each file is FIND
. Here’s the general syntax to use:
FOR %f IN (filespec) DO FIND "string" %f
Replace filespec
with the file specification you want to use and string
with the string you want to search for. For example, the following command runs through all the .doc
files in the current folder and searches each file for the string Thanksgiving
:
FOR %f IN (*.doc) DO FIND "Thanksgiving" %f
If the file specification will match files with spaces in their names, you need to surround the last %f
parameter with quotation marks, like so:
FOR %f IN (*.doc) DO FIND "Thanksgiving" "%f"
One of the most common uses of the FIND
command is as a filter in pipe operations. In this case, instead of a filename, you pipe the output of another command through FIND
. In this case, FIND
searches this input for a specified string and, if it finds a match, displays the line that contains the string.
For example, the last line of a DIR
listing tells you the number of bytes free on the current drive. Rather than wade through the entire DIR
output just to get this information, use this command instead:
dir | find "free"
You’ll see something like the following:
2 Dir(s) 28,903,331,184 bytes free
FIND
scours the DIR
listing piped to it and looks for the word free. You can use this technique to display specific lines from, say, a CHKDSK
report. For example, searching for bad finds the number of bad sectors on the disk.
REN
: Renaming a File or FolderYou use the REN
(or RENAME
) command to change the name of one or more files and folders. Here’s the syntax:
REN old_filename new_filename
|
The original filename |
|
The new filename |
For example, the following command renames Budget 2017.xlsx
to Budget 20187.xlsx
:
ren "Budget 2017.xlsx" "Budget 2018.xlsx"
A simple file or folder rename such as this probably isn’t something you’ll ever fire up a command-line session to do because renaming a single object is faster and easier in File Explorer. However, the real power of the REN
command is that it accepts wildcards in the file specifications. This enables you to rename several files at once—something you can’t do in File Explorer.
For example, suppose you have a folder full of files, many of which contain 2017 somewhere in the filename. To rename all those files by changing 2017 to 2018, you would use the following command:
ren *2017* *2018*
Similarly, if you have a folder full of files that use the .htm
extension and you want to change each extension to .asp, you use the following command:
ren *.htm *.asp
Note that for these multiple-file renames to work, in most cases the original filename text and the new filename text must be the same length. For example, digital cameras often supply photos with names such as img_1234.jpg
and img_5678.jpg
. If you have a number of related photos in a folder, you might want to give them more meaningful names. If the photos are from a vacation in Rome, you might prefer names such as Rome_Vacation_1234.jpg
and Rome_Vacation_5678.jpg
. Unfortunately, the REN
command can’t handle this type of change. However, it can rename the files to Rome_1234.jpg
and Rome_5678.jpg
:
ren img_* Rome*
The exception to the same-length rule is if the replacement occurs at the end of the filenames. For example, the following command renames all files with the .jpeg
extension to .jpg
:
ren *.jpeg *.jpg
REPLACE
: Smarter File CopyingIf there was such a thing as a Most Underrated Command award, REPLACE
would win it hands down. This command, which you almost never hear about, can do three very useful (and very different) things:
It copies files, but only if their names match those in the target directory.
It copies files, but only if their names don’t exist in the target directory.
It copies files, but only if their names match those in the target directory and the matching files in the target directory are older than the files being copied.
Here’s the syntax:
REPLACE source_files target /A /U /P /R /S /W
|
Indicates the path and file specification of the files you want to copy. |
|
Specifies the folder to which you want to copy the files. |
|
Copies only new files to the |
|
Copies files that have the same name in the |
|
Prompts you for confirmation before replacing files. |
|
Replaces read-only files. |
|
Replaces files in the |
|
Waits for you to insert a disk before starting. |
If you don’t specify switches, REPLACE
copies a file from the source folder to the target folder if and only if it finds a file with a matching name in the target.
More useful is the REPLACE
command’s updating mode, where it copies a file from the source folder to the target folder if and only if it finds a file with a matching name in the target and that target file is older than the source file. A good example where updating comes in handy is copying some files to a disk or memory card so that you can use them on another machine (such as taking files from your computer at work to use them at home). When you need to copy the files back to the first machine, the following REPLACE
command does the job. (This assumes the disk or memory card is in the G: drive.)
replace g:*.* %UserProfile% /s /u
For each file on the G: drive, REPLACE
looks for matching filenames anywhere in the %UserProfile%
folder and its subfolders (thanks to the /S
switch) and replaces only the ones that are newer (the /U
switch).
What if you created some new files on the other computer? To copy those to the first machine, use the /A
switch, as follows:
replace g:*.* %UserProfile%Documents /a
In this case, REPLACE
copies a file from the G: drive only if it doesn’t exist in the %UserProfile%Documents
folder. (You must specify a target folder because you can’t use the /S
switch with /A
.)
SORT
: Sorting the Contents of a FileWhen you obtain a file from the Internet or some other source, the data in the file may not appear in the order you want. What we usually do in such cases is import the file into Word or Excel and then use the program’s Sort feature. This process sometimes involves extra steps (such as converting text to a table in Word), so it’s not always an efficient way to work.
If the file is text, it’s often easier and faster to run the SORT
command-line tool. By default, SORT
takes the content of the file, sorts it in ascending alphanumeric order (0 to 9, then a to z, and then A to Z) starting at the beginning of each line in the file, and then displays the sorted results. You can also run descending order sorts, write the results to the same file or another file, and more. Here’s the syntax:
SORT [input_file] [/+n] [/R] [/L locale] [/M kilobytes] [/REC characters] [/T temp_folder] [/O output_file]
For example, the following SORT
command sorts the data in records.txt
and stores the results in sorted_records.txt
:
sort records.txt sorted_records.txt
XCOPY:
Advanced File CopyingThe XCOPY
command is one of the most powerful of the file management command-line tools, and you can use it for some fairly sophisticated file copying operations. Here’s the syntax for XCOPY
:
XCOPY source destination [/A | /M] [/B] [/C] [/D[:mm-dd--yyyy]] [/EXCLUDE:file1[+file2[+file3]]] [/F] [/G] [/H] [/I] [/J] [/K] [/L] [/N] [/O] [/P] [/Q] [/R] [/S [/E]] [/T] [/U] [/V] [/W] [/X] [/Y | -Y] [/Z]
In its basic form, XCOPY
works just like COPY
. So, for example, to copy all the .doc files in the current folder to a folder called Documents in the G: drive, use the following command:
xcopy *.doc g:documents
Besides being faster, XCOPY
also contains a number of features not found in the puny COPY
command. Think of it as COPY
on steroids. (The X in XCOPY
means that it’s an extended COPY
command.) For example, suppose you want to copy all the .doc files in the current folder and all the .doc files in any attached subfolders to G:Documents
. With COPY
, you first have to create the appropriate folders on the destination partition and then perform separate COPY
commands for each folder, which is not very efficient, to say the least. With XCOPY
, all you do is add a single switch:
xcopy *.doc g:documents /s xcopy *.bat d:atch /s
The /S
switch tells XCOPY
to copy the current folder and all nonempty subfolders, and to create the appropriate folders in the destination, as needed. (If you want XCOPY
to copy empty subfolders, include the /E
switch as well.)
Another useful feature of XCOPY
is the ability to copy files by date. This is handy for performing incremental backups of files that you modified on or after a specific date. For example, suppose you keep your word processing documents in %UserProfile%Documents
and you want to make backup copies in your Windows 10 user share of all the .doc
files that have changed since August 23, 2016. You can do this by using the following command:
xcopy %userprofile%documents*.doc \serverusers\%Username% /d:08-23-2016
It’s common to use XCOPY
in batch files, but take care to handle errors. For example, what if a batch file tries to use XCOPY
but there’s not enough memory? Or what if the user presses Ctrl+C during the copy? It might seem impossible to check for these kinds of errors; yet doing it is not only possible but also really quite straightforward.
When certain commands finish, they always file a report on the progress of the operation. This report, or exit code, is a number that specifies how the operation went. For example, Table B.3 lists the exit codes that the XCOPY
command uses.
Exit Code |
What It Means |
0 |
Everything’s okay; the files were copied. |
1 |
Nothing happened because no files were found to copy. |
2 |
The user pressed Ctrl+C to abort the copy. |
4 |
The command failed because there wasn’t enough memory or disk space, something was wrong with the command’s syntax, or an invalid drive name was entered. |
5 |
The command failed because of a disk error. |
What does all this mean for your batch files? You can use a variation of the IF
command—IF ERRORLEVEL
—to test for these exit codes. For example, here’s a batch file that uses some of the XCOPY
exit codes to check for errors:
@ECHO OFF XCOPY %1 %2 IF ERRORLEVEL 4 GOTO ERROR IF ERRORLEVEL 2 GOTO CTRL+C IF ERRORLEVEL 1 GOTO NO_FILES GOTO DONE :ERROR ECHO Bad news! The copy failed because there wasn't ECHO enough memory or disk space or because there was ECHO something wrong with your file specs . . . GOTO DONE :CTRL+C ECHO Hey, what gives? You pressed Ctrl+C to abort . . . GOTO DONE :NO_FILES ECHO Bad news! No files were found to copy . . . :DONE
note
How does a batch file know what a command’s exit code was? When Windows 10 gets an exit code from a command, it stores that code in a special data area set aside for exit code information. When Windows 10 sees the IF ERRORLEVEL
command in a batch file, it retrieves the exit code from the data area so that it can be compared to whatever is in the IF
condition.
As you can see, the ERRORLEVEL
conditions check for the individual exit codes and then use GOTO
to jump to the appropriate label.
One of the most important things to know about the IF
ERRORLEVEL test is how Windows 10 interprets it. For example, consider the following IF
command:
IF ERRORLEVEL 2 GOTO CTRL+C
Windows 10 interprets this command as “If the exit code from the last command is equal to or greater than 2, jump to the Ctrl+C label.” This has two important consequences for your batch files:
The test IF ERRORLEVEL 0
doesn’t tell you much because it’s always true. If you just want to find out whether the command failed, use the test IF NOT ERRORLEVEL 0
.
To get the correct results, always test the highest ERRORLEVEL
first and then work your way down.
System management is one of those catchall terms that encompasses a wide range of tasks, from simple adjustments such as changing the system date and time to more complex tweaks such as modifying the Registry. Windows 10’s command-line system management tools also enable you to monitor system performance, shut down or restart the computer, and even modify the huge Windows Management Instrumentation (WMI) interface. Table B.4 lists the system management command-line tools that apply to Windows 10.
Tool |
Description |
|
Displays or modifies the Boot Manager startup parameters |
|
Displays or changes the number of active console code pages |
|
Displays or sets the system date |
|
Creates a custom event in an event log |
|
Adds, modifies, displays, and deletes Registry keys and settings |
|
Registers dynamic link library (DLL) files as command components in the Registry |
|
Shuts down or restarts Windows 10 or a remote computer |
|
Displays a wide range of detailed configuration information about the computer |
|
Displays or sets the system time |
|
Monitors a performance counter |
|
Displays information about the current user, including the domain name (not applicable to Windows 10), computer name, username, security group membership, and security privileges |
|
Operates the Windows Management Instrumentation command-line tool that provides command-line access to the WMI interface |
The next few sections take more detailed looks at five of these command-line tools: REG
, SHUTDOWN
, SYSTEMINFO
, TYPEPERF
, and WHOAMI
.
REG
: Working with Registry Keys and SettingsIn Chapter 29, “Editing the Windows Registry,” you learned how to view, add, and modify Registry keys and settings using the Registry Editor. That’s the easiest and safest way to make Registry changes. However, there may be some settings that you change quite often. In such cases, it can become burdensome to be frequently launching the Registry Editor and changing the settings. A better idea is to create a shortcut or batch file that uses the REG command-line tool to make your Registry changes for you.
REG
actually consists of 11 subcommands, each of which enables you to perform different Registry tasks:
We won’t go through all these commands. Instead, we’ll focus on the three most common Registry tasks: viewing, adding, and changing Registry data.
To view the current value of the Registry setting, you use the REG QUERY command:
REG QUERY KeyName [/V ValueName | /VE] [/C] [/D] [/E] [/F data] [/K | [/S] [/SE separator] [/T type] [/Z] [/reg:32 | /reg:64]
|
Specifies the Registry key that contains the setting or settings you want to view. The KeyName must include a root key value: HKCR, HKCU, HKLM, HKU, or HKCC. Place quotation marks around key names that include spaces. |
|
Specifies the Registry setting in KeyName that you want to view. |
|
Tells REG to look for empty settings (that is, settings with a null value). |
|
Runs a case-sensitive query. |
|
Returns only exact matches. |
|
Specifies the data that REG should match in the KeyName settings. |
|
Queries only key names, not settings. |
|
Tells REG to query the subkeys of KeyName. |
|
Defines the separator to search for in REG_MULTI_SZ settings. |
|
Specifies the setting type or types to search: REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_BINARY, or REG_NONE. |
|
Tells REG to include the numeric equivalent of the setting type in the query results. |
|
Tells REG to access KeyName using the 32-bit Registry view. |
|
Tells REG to access KeyName using the 64-bit Registry view. |
For example, if you want to know the current value of the RegisteredOwner
setting in HKLM
SoftwareMicrosoftWindows NTCurrentVersion, run the following command:
reg query "hklmsoftwaremicrosoftwindows ntcurrentversion" registeredowner
The Registry Editor has a Find
command that enables you to look for text within the Registry. However, it would occasionally be useful to see a list of the Registry keys and settings that contains a particular bit of text. You can do this by using the /F
switch. For example, suppose you want to see a list of all the HKLM keys and settings that contain the text Windows Defender. Here’s a command that will do this:
reg query hklm /f "Windows Defender" /s
To add a key or setting to the Registry, use the REG ADD
command:
REG ADD KeyName [/V ValueName | /VE] [/D data] [/F | [/S separator] [/T type] [/reg:32 | /reg:64]
|
Specifies the Registry key that you want to add or to which you want to add a setting. The KeyName must include a root key value: HKCR, HKCU, HKLM, HKU, or HKCC. Place quotation marks around key names that include spaces. |
|
Specifies the setting you want to add to KeyName. |
|
Tells REG to add an empty setting. |
|
Specifies the data that REG should use as the value for the new setting. |
|
Modifies an existing key or setting without prompting to confirm the change. |
|
Defines the separator to use between multiple instances of data in a new REG_MULTI_SZ setting. |
|
Specifies the setting type: REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_DWORD_LITTLE_ENDIAN, REG_BINARY, or REG_LINK. |
|
Tells REG to access KeyName using the 32-bit Registry view. |
|
Tells REG to access KeyName using the 64-bit Registry view. |
For example, the following command adds a key named MySettings
to the HKCU root key:
reg add hkcuMySettings
Here’s another example that adds a setting named CurrentProject
to the new MySettings
key and sets the value of the new setting to Win 8 In Depth
:
reg add hkcuMySettings /v CurrentProject /d "Win 8 In Depth"
If you want to make changes to an existing setting, run REG ADD on the setting. For example, to change the HKCUMySettingsCurrentProject
setting to Windows 10 In Depth
, you run the following command:
reg add hkcuMySettings /v CurrentProject /d "Windows 10 In Depth"
tip
To avoid being prompted when changing existing settings, add the /F
switch to the REG ADD
command.
Windows 10 responds with the following prompt:
Value CurrentProject exists, overwrite (Yes/No)?
To change the existing value, press Y and press Enter.
SHUTDOWN
: Shutting Down or Restarting the SystemYou can use the SHUTDOWN
command to restart or shut down your computer (or a remote computer on your network). Here’s the full syntax:
SHUTDOWN [[/R] | [/G] | [/S] | [/SG] | [/L] | [/H] | [/I] | [/P] | [/E] | [/A] | [/O]] [/F | [/HYBRID] [/SOFT] [FW] [/D [P|U:]major:minor] [/M \ComputerName] [/T seconds] [/C "comment"]
|
Restarts the computer. |
||
|
Restarts the computer and, after you log on, restarts any applications that were running. |
||
|
Shuts down the computer. |
||
|
Shuts down the computer and then restarts any registered applications on the next boot. |
||
|
Logs off the current user immediately. |
||
|
Puts the computer into hibernation, if the computer supports hibernation mode. |
||
|
Displays the Remote Shutdown dialog box, which enables you to specify many of the options provided by these switches. |
||
|
Turns off the local computer immediately (that is, without the usual warning interval). |
||
|
Enables you to document the reason for an unexpected shutdown. |
||
|
Cancels the pending restart or shutdown. |
||
|
Restarts the PC into the Recovery Environment. You must also include the /R switch. |
||
|
Forces all running programs on the target computer to shut down without warning. This, obviously, is dangerous and should be used only as a last resort. |
||
|
Shuts down the PC and prepares it for a fast restart. You must also include the /S switch. |
||
|
Skips hardware initialization during the next reboot. You must also include the /S switch. |
||
|
During the next restart, automatically boots the PC into its firmware setup utility. You must also include the /S switch. |
||
|
Specifies the reason for the shutdown. Include P: to indicate the shutdown is planned; include U: to indicate the shutdown is unplanned. Use values between 0 and 255 for major and between 0 and 65535 for minor. Windows also defines a number of predefined values for the major and minor parameters: |
||
|
|
|
Reason |
|
0 |
0 |
Other |
|
0 |
5 |
Other Failure: System Unresponsive |
|
1 |
Hardware: Maintenance |
|
|
1 |
2 |
Hardware: Installation |
|
2 |
2 |
Operating System: Recovery |
|
2 |
3 |
Operating System: Upgrade |
|
2 |
4 |
Operating System: Reconfiguration |
|
2 |
16 |
Operating System: Service Pack |
|
2 |
17 |
Operating System: Hot Fix |
|
2 |
18 |
Operating System: Security Fix |
|
4 |
1 |
Application: Maintenance |
|
4 |
2 |
Application: Installation |
|
4 |
5 |
Application: Unresponsive |
|
4 |
6 |
Application: Unstable |
|
5 |
15 |
System Failure: Stop Error |
|
5 |
19 |
Security Issue |
|
5 |
20 |
Loss of Network Connectivity |
|
6 |
11 |
Power Failure: Cord Unplugged |
|
6 |
12 |
Power Failure: Environment |
|
7 |
0 |
Legacy API Shutdown |
/M \ComputerName |
Specifies the remote computer you want to shut down. |
||
|
Specifies the number of seconds after which the computer is shut down. The default is 30 seconds, and you can specify any number up to 600. |
||
|
The comment text (which can be a maximum of 127 characters) appears in the dialog box and warns the user of the pending shutdown. This comment text also appears in the shutdown event that is added to the System log in Event Viewer. (Look for an Event ID of 1074.) |
For example, to restart your computer immediately, use the following command:
shutdown /r /t 0
If you’ve launched a restart or shutdown using some nonzero value for /T
, and you need to cancel the pending shutdown, run SHUTDOWN
with the /A
switch before the timeout interval is over:
shutdown /a
SYSTEMINFO
: Returning System Configuration DataIf you want to get information about various aspects of your computer, a good place to start is the SYSTEMINFO
command-line tool, which displays data about the following aspects of your system:
The operating system name, version, manufacturer, and configuration type
The registered owner and organization
The original install date
The system boot time
The computer manufacturer, model, and system type
The system processors
The BIOS version
The total and available physical memory
The paging file’s maximum size, available size, in-use value, and location
The installed hotfixes
The network interface card data, such as the name, connection, DHCP status, and IP address (or addresses)
You can see all this data (and more), as well as control the output, by running SYSTEMINFO
with the following syntax:
SYSTEMINFO [/S computer] [/U [domain]username] [/P password] [/FO format] [/NH]
|
Specifies the name of the remote computer for which you want to view the system configuration. |
|
Indicates the username and, optionally, the domain of the account under which you want to run the SYSTEMINFO command. |
|
Specifies the password of the account you specified with /U. |
|
Indicates the output format, where format is one of the following values: |
|
table—The output is displayed in a row-and-column format, with headers in the first row and values in subsequent rows. |
|
list—The output is displayed in a two-column list, with the headers in the first column and values in the second column. |
|
csv—The output is displayed with headers and values separated by commas. The headers appear on the first line. |
|
Tells SYSTEMINFO not to include column headers when you use the /FO switch with either table or csv. |
The output of SYSTEMINFO
is quite long, so pipe it through the MORE
command to see the output one screen at a time:
systeminfo | more
If you want to examine the output in another program or import the results into Excel or Access, redirect the output to a file and use the appropriate format. For example, Excel can read .csv
files, so you can redirect the SYSTEMINFO
output to a .csv
file while using csv
as the output format:
systeminfo /fo csv > systeminfo.csv
TYPEPERF
: Monitoring PerformanceIn Chapter 23, “Windows Management Tools,” you learned how to use the Performance Monitor utility to track the real-time performance of counters in various categories such as processor and memory.
For the details on the Performance Monitor utility, see “Using the Performance Monitor,” p. 530.
You can get the same benefit without the Performance Monitor GUI by using the powerful TYPEPERF
command-line tool. Here’s the syntax:
TYPEPERF [
counter1 [counter2 ...]] [-CF file] [-O file] [-F format]
[-SI interval] [-SC samples] [-Q [object]] [-QX [object]]
[-CONFIG file] [-S computer] [-Y]
The official syntax of a counter path looks like this:
[\Computer]Object([Parent/][Instance][#Index])Counter
|
The computer on which the counter is to be monitored. If you omit a computer name, TYPEPERF monitors the counter on the local computer. |
|
The performance object—such as Processor, Memory, or PhysicalDisk—that contains the counter. |
|
The container instance of the specified Instance. |
|
The instance of the Object, if it has multiple instances. For example, in a two- (or dual-core) processor system, the instances are 0 (for the first processor), 1 (for the second processor), and Total (for both processors combined). You can also use an asterisk (*) to represent all the instances in Object. |
|
The index number of the specified Instance. |
|
The name of the performance counter. You can also use an asterisk (*) to represent all the counters in Object(Instance). |
In practice, however, you rarely use the Computer
, Parent
, and Index
parts of the path, so most counter paths use one of the following two formats:
ObjectCounter Object(Instance)Counter
For example, here’s the path for the Memory
object’s Available MBytes
counter:
MemoryAvailable MBytes
Here’s a TYPEPERF
command that displays five samples of this counter:
typeperf "MemoryAvailable Mbytes" -sc 5
Similarly, here’s the path for the Processor object’s % Processor Time
counter, using the first processor instance:
Processor(0)\% Processor Time
Here’s a TYPEPERF
command that displays 10 samples of this counter every 3 seconds and saves the results to a file named ProcessorTime.txt
:
typeperf "Processor(0)\% Processor Time" -sc 10 -si 3 -o ProcessorTime.txt
To use the -CONFIG
parameter with TYPEPERF
, you must create a text file that stores the command-line parameters you want to use. This configuration file consists of a series of parameter/value pairs that use the following general format:
[Parameter] Value
Here, Parameter
is text that specifies a TYPEPERF
parameter—such as F for the -F
parameter and S
for the -S
parameter. Use C
to specify one or more counter paths, and Value
is the value you want to assign to the parameter.
For example, consider the following command:
typeperf "PhysicalDisk(_Total)\% Idle Time" -si 5 -sc 10 -o idletime.txt
To run the same command using the -CONFIG
parameter, you first need to create a file with the following text:
[c] PhysicalDisk(_Total)\% Idle Time [si] 5 [sc] 10 [o] idletime.txt
If this file is named IdleTimeCounter.txt
, you can run it at any time with the following command (assuming IdleTimeCounter.txt
resides in the current folder):
typeperf -config IdleTimeCounter.txt
WHOAMI
: Getting Information About the Current UserThe WHOAMI
command gives you information about the user who is currently logged on to the computer:
WHOAMI [/UPN | /FQDN | LOGONID] [/USER | /GROUPS | /CLAIMS | /PRIV] [/ALL] [/FO format] [/NH]
(Domains only) Returns the current user’s name using the user principal name (UPN) format. |
|
|
(Domains only) Returns the current user’s name using the fully qualified domain name (FQDN) format. |
|
Returns the current user’s security identifier (SID). |
|
Returns the current username using the computeruser format. |
|
Returns the groups of which the current user is a member. |
|
(Domains only) Returns the current user’s claims. |
|
Returns the current user’s privileges. |
|
Returns the current user’s SID, username, groups, and privileges. |
|
Specifies the output format, where format is one of the following values: |
|
table—The output is displayed in a row-and-column format, with headers in the first row and values in subsequent rows. |
|
list—The output is displayed in a two-column list, with headers in the first column and values in the second column. |
|
csv—The output is displayed with headers and values separated by commas. The headers appear on the first line. |
|
Tells WHOAMI not to display column headers in the output. |
You probably won’t use this command often on the Windows 10 computer because you’ll almost always be logged on as administrator. However, WHOAMI
is useful when you’re working on a client computer and you’re not sure who is currently logged on.
For example, the following command redirects the current user’s SID, username, groups, and privileges to a file named whoami.txt
using the list format:
whoami /all /fo list > whoami.txt
You can script your user and group chores by taking advantage of the NET USER
and NET LOCALGROUP commands. These commands enable you to add users, change passwords, modify accounts, add users to groups, and remove users from groups. Note that you must run these commands under the Administrator account, so press Windows Logo+X, click Command Prompt (Admin), and then enter your User Account Control credentials.
NET USER
: Working with UsersYou use the NET USER
command to add users, set account passwords, disable accounts, set account options (such as the times of day the user is allowed to log on), and remove accounts. For local users, the NET USER command has the following syntax:
NET USER [username [password | * | /RANDOM] [/ADD] [/DELETE] [options]]
Specifies the name of the user you want to add or work with. If you run |
|
|
Indicates the password you want to assign to the user. If you use *, Windows 10 prompts you for the password; if you use the / |
|
Creates a new user account. |
|
Deletes the specified user account. |
|
These are optional switches you can append to the command: |
|
|
|
|
|
|
|
|
|
/PASSWORDREQ:{YES | NO}—Specifies whether the user is required to have a password. |
|
|
|
|
|
M-F,9am-5pm M,W,F,08:00-13:00 Sa,12pm-6pm;Su,1pm-5pm |
caution
If you use the /RANDOM
switch to create a random password, be sure to make a note of the new password so that you can communicate it to the new user.
Note, too, that if you execute NET USER
without parameters, it displays a list of the local user accounts.
tip
If you want to force a user to log off when his logon hours expire, open the Local Group Policy Editor and select Computer Configuration, Windows Settings, Security Settings, Local Policies, Security Options. In the Network Security category, enable the Force Logoff When Logon Hours Expire policy.
NET LOCALGROUP
: Working with GroupsYou use the NET LOCALGROUP
command to add users to and remove users from a specified security group. NET LOCALGROUP
has the following syntax:
NET LOCALGROUP [group name1 [name2 ...] {/ADD | /DELETE}
|
Specifies the name of the security group with which you want to work. |
|
Specifies one or more usernames you want to add or delete, separated by spaces. |
|
Adds the user or users to the group. |
|
Removes the user or users from the group. |
NET USE
: Mapping FoldersYou can also map a network folder to a local drive letter by using a Command Prompt session and the NET USE
command. Although you probably won’t use this method very often, it’s handy to know how it works, just in case. Here’s the basic syntax:
NET USE [drive] [share] [password] [/USER:user] [/PERSISTENT:[YES | NO]] | /DELETE]
|
Specifies the drive letter (following by a colon) of the local drive to which you want the network folder mapped. |
|
Indicates the network address of the folder. |
|
Specifies the password required to connect to the shared folder (that is, the password associated with the username, specified next). |
|
Specifies the username you want to use to connect to the shared folder. |
|
Enables you to reconnect the mapped network drive the next time you log on when you add |
|
Deletes the existing mapping that’s associated with |
For example, the following command maps the shared folder \PAULSPCPaulWritingBooks
to the Z: drive:
net use z: \paulspcpaulwritingooks /persistent:yes
Windows 10 TCP/IP comes with a few command-line utilities you can use to review your TCP/IP settings and troubleshoot problems. Here’s a list of the available utilities:
ARP
—This utility displays (or modifies) the IP-to-Ethernet or IP-to-Token Ring address translation tables used by the Address Resolution Protocol (ARP) in TCP/IP. Enter the command arp -?
for the syntax.
NBTSTAT
—This utility displays the protocol statistics and the current TCP/IP connections using NBT (NetBIOS over TCP/IP). Enter nbtstat -?
for the syntax.
NETSTAT
—This utility displays the protocol statistics and current TCP/IP connections. Enter the command netstat -?
to display the syntax.
NSLOOKUP
—This utility queries the Domain Name System (DNS) that associates host and domain names with IP addresses, DNS servers, mail servers, and so on. Enter commands nslookup
then help
to display the syntax. (It's a complex tool; if we had room, we could devote an entire chapter to it.)
PING
—This utility can check a network connection to a remote computer. This is one of the most commonly used TCP/IP diagnostic tools, so we describe it in more detail in Chapter 17, “Troubleshooting an Internet Connection.”
ROUTE
—This utility can be used to manipulate a network routing table (LMHOSTS). Enter route
-? for the syntax.
TRACERT
—This utility can check the route taken to a remote host. We also explain this valuable diagnostic command in Chapter 17.
IPCONFIG
—This utility displays the current TCP/IP network configuration. If you run the command ipconfig
without switches, the utility returns your system’s current IP address, subnet mask, and default gateway. If you run the command ipconfig /all
, the utility returns more detailed information.
3.145.131.238