B

COMMAND-LINE UTILITIES

Working with Disk Management Tools

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.

Table B.1 Windows 10’s Command-Line Disk Management Tools

Tool

Description

CHKDSK

Checks a specified volume for errors.

CHKNTFS

Configures automatic disk checking.

CONVERT

Converts a specified volume to a different file system.

DEFRAG

Defragments a specified volume.

DISKCOMP

Compares the contents of two floppy disks. (This tool does not compare hard disks or other types of removable media, such as memory cards.)

DISKCOPY

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.)

DISKPART

Enables you to list, create, select, delete, and extend disk partitions.

EXPAND

Extracts one or more files from a compressed file, such as a.cab file found on some installation discs.

FORMAT

Formats the specified volume.

FSUTIL

Performs a number of file system tasks.

LABEL

Changes or deletes the name of a specified volume.

MOUNTVOL

Creates, displays, or deletes a mount point.

VOL

Displays the name and serial number of a specified volume.

CHKDSK: Checking for Hard Disk Errors

In 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]

volume

The drive letter (followed by a colon) or mount point.

filename

On FAT16 and FAT32 disks, the name of the file to check. Include the path if the file isn’t in the current folder.

/F

Tells CHKDSK to fix errors automatically and then mark the volume as clean (that is, error-free). This is the same as running the Check Disk GUI with the Automatically Fix File System Errors option activated.

/V

Runs CHKDSK in verbose mode. On FAT16 and FAT32 drives, CHKDSK displays the path and name of every file on the disk; on NTFS drives, CHKDSK displays cleanup messages, if any.

/R

Tells CHKDSK to scan the disk surface for bad sectors and recover data from the bad sectors, if possible. (The /F switch is implied.) This is the same as running the Check Disk GUI with the Scan For and Attempt Recovery of Bad Sectors option activated.

/B

Tells CHKDSK to clear the list of bad sectors on the disk and then recheck the entire disk. Including this parameter is the same as including the /R parameter.

/X

On NTFS nonsystem disks that have open files, forces the volume to dismount, invalidates the open file handles, and then runs the scan. (The /F switch is implied.)

/I

On NTFS disks, tells CHKDSK to check only the file system’s index entries.

/C

On NTFS disks, tells CHKDSK to skip the checking of cycles within the folder structure. This is a rare error, so using /C to skip the cycle check can speed up the disk check.

/L:[size]

On NTFS disks, tells CHKDSK to set the size of its log file to the specified number of kilobytes. The default size is 65,536, which is plenty big enough for most systems, so you should never need to change the size. Note that if you include this switch without the size parameter, CHKDSK tells you the current size of the log file.

/scan

On NTFS disks, scans the volume for errors while leaving the volume online.

/forceofflinefix

On NTFS disks, forces CHKDSK to queue all volume errors for offline repair, even errors that can be fixed while the volume is online. The /scan parameter must also be included.

/perf

On NTFS disks, requests more system resources to increase scan performance. The /scan parameter must also be included.

/spotfix

On NTFS disks, spot fixes the volume.

/freeorphanedchains

On FAT/FAT32 disks, tells CHKDSK to free any chains of orphaned clusters for other files to use. If you don’t include this switch, CHKDSK tries to recover the data from orphaned clusters.

/markclean

On FAT/FAT32 disks, marks the volume as clean if CHKDSK doesn’t find errors. This works even if you don’t include the /F switch.

/offlinescanandfix

On NTFS disks, takes the volume offline and runs a scan and repair on the volume.

/sdcleanup

On NTFS disks, removes security descriptor data that is no longer needed. (The /F switch is implied.)

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 Checks

You 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]]

volume

Specifies a drive letter (followed by a colon) or mount point.

/C volume

Tells CHKNTFS to schedule an automatic startup disk check for the specified volume. You can specify multiple volumes (separated by spaces).

/X volume

Tells CHKNTFS to exclude the specified volume from an automatic startup disk check. You can specify multiple volumes (separated by spaces).

/D

Tells CHKNTFS to exclude all volumes from an automatic startup disk check.

/T:[time]

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 Drive

In 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]

disks

Specifies the drive letter (followed by a colon) of each disk you want to defragment. (Separate multiple drives with a space.)

task(s)

As this book went to press, Microsoft had not provided information on this new parameter.

/A

Tells DEFRAG only to analyze the disk.

/C

Tells DEFRAG to defragment all the system’s drives.

/D

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).

/E

Tells DEFRAG to defragment all the system’s drives except those specified with the disks parameter.

/G

Optimize the drive's storage tiers.

/H

Runs DEFRAG with a higher program priority for better performance.

/I n

Tells DEFRAG to run tier optimization for at most n seconds.

/K

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.

/L

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.

/M

Tells DEFRAG to defragment all the specified drives at the same time (in parallel).

/O

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.

/T

Tells DEFRAG to show the progress of an already running defrag.

/U

Tells DEFRAG to show the progress of the defrag.

/V

Runs DEFRAG in verbose mode, which displays both the analysis report and the defragmentation report.

/X

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.

Working with File and Folder Management Tools

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.

Table B.2 Windows 10’s Command-Line File and Folder Management Tools

Tool

Description

ATTRIB

Displays, applies, or removes attributes for the specified file or folder.

CD

Changes to the specified folder.

COMP

Compares the contents of two specified files, byte by byte.

COMPACT

Displays or modifies the compression settings for the specified file or folder (which must be located on an NTFS partition).

COPY

Creates a copy of the specified file or folder in another location.

DEL

Deletes the specified file or folder.

DIR

Displays a directory listing for the current folder or for the specified file or folder.

FC

Compares the content of two specified files.

FIND

Searches for and displays all the instances of a specified string in a file.

FINDSTR

Uses a regular expression to search for and display all the instances of a specified string in a file.

MKDIR

Creates the specified folder.

MOVE

Moves the specified file or folder to another location.

REN

Changes the name of the specified file or folder.

REPLACE

Replaces files in the destination folder with files in the source folder that have the same name.

RMDIR

Deletes the specified folder.

SORT

Sorts the specified file and then displays the results.

SFC

Runs the System File Checker, which scans and verifies the protected Windows 10 files.

TAKEOWN

Enables an administrator to take ownership of the specified file.

TREE

Displays a graphical tree diagram showing the subfolder hierarchy of the current folder or the specified folder.

WHERE

Searches for and displays all the files that match a specified pattern in the current folder and in the PATH folders.

XCOPY

Creates a copy of the specified file or folder in another location. This tool offers many more options than the COPY command.

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 Attributes

A 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]]

+A

Sets the archive attribute.

-A

Clears the archive attribute.

+H

Sets the hidden attribute.

-H

Clears the hidden attribute.

+I

Sets the content not indexed attribute.

-I

Clears the content not indexed attribute.

+O

Sets the offline attribute.

-O

Clears the offline attribute.

+P

Sets the pinned attribute.

-P

Clears the pinned attribute.

+R

Sets the read-only attribute.

-R

Clears the read-only attribute.

+S

Sets the system attribute.

-S

Clears the system attribute.

+U

Sets the integrity attribute.

-U

Clears the integrity attribute.

+V

Sets the integrity attribute.

-V

Clears the integrity attribute.

+X

Sets the no scrub attribute.

-X

Clears the no scrub attribute.

filename

Specifies the file or files you want to work with.

/S

Applies the attribute change to the matching files in the current folder and all of its subfolders.

/D

Applies the attribute change only to the current folder’s subfolders. You must use this switch with /S.

/L

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 File

You 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

/C

Displays the number of times that string appears in filename.

/I

Performs a search that is not case sensitive.

/N

Displays each match of string in filename with the line number in filename where each match occurs.

/V

Displays the lines in filename that don’t contain string.

/OFF[LINE]

Tells FIND to not skip files that have their offline attribute set.

string

Specifies the string you want to search for.

filename

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 Folder

You 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

old_filename

The original filename

new_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 Copying

If 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

source_files

Indicates the path and file specification of the files you want to copy.

target

Specifies the folder to which you want to copy the files.

/A

Copies only new files to the target folder. You can’t use this switch with /S or /U.

/U

Copies files that have the same name in the target folder and that are newer than the matching files in the target folder. You can’t use this switch with /A.

/P

Prompts you for confirmation before replacing files.

/R

Replaces read-only files.

/S

Replaces files in the target folder’s subfolders. You can’t use this switch with /A.

/W

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 File

When 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]

input_file

Names the file you want to sort.

/+n

Specifies the starting character position (n) of the sort. The default is 1 (that is, the first character on each line in the file).

/R

Sorts the file in descending order (Z to A, then z to a, and then 9 to 0).

/L locale

Specifies a locale for sorting other than the default system locale. Your only choice here is to use "C" to sort the file using the binary values for each character.

/M kilobytes

Specifies the amount of memory, in kilobytes, that SORT uses during the operation. If you don’t specify this value, SORT uses a minimum of 160KB and a maximum of 90% of available memory.

/REC characters

Specifies the maximum length, in characters, of each line in the file. The default value is 4,096 characters, and the maximum value is 65,535 characters.

/T temp_folder

Specifies the folder that SORT should use to hold the temporary files it uses during the sort.

/O output_file

Specifies the file that SORT should create to store the results of the sort. You can specify a different file or the input 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 Copying

The 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]

source

Specifies the path and names of the files you want to copy.

destination

Indicates the location where you want the source files copied.

[/A]

Tells XCOPY to copy only those source files that have their archive attribute turned on. The archive attribute is not changed. If you use /A, you can’t also use /M.

[/M]

Tells XCOPY to copy only those source files that have their archive attribute turned on. The archive attribute is turned off. If you use /M, you can’t also use /A.

[/B]

Tells XCOPY to copy the file's symbolic link instead of the file itself.

[/C]

Tells XCOPY to ignore any errors that occur during the copy operation; otherwise, XCOPY aborts the operation if an error occurs.

[/D[:mm-dd-yyyy]]

Copies only those source files that changed on or after the date specified by mm-dd-yyyy. If you don’t specify a date, using /D tells XCOPY to copy those source files that are newer than destination files that have the same name.

[/EXCLUDE: file1 [+file2[+file3]]]

Tells XCOPY to not copy the files or file specification given by file1, file2, file3, and so on.

[/F]

Displays the source and destination filename during the copy operation.

[/G]

Creates decrypted copies of encrypted source files.

[/H]

Tells XCOPY to include in the copy operation any hidden and system files in the source folder.

[/I]

Tells XCOPY to create the destination folder. For this to work, the source value must be a folder or a file specification with wildcards.

[/J]

Tells XCOPY to use unbuffered input/output during the copy operation, which improves performance for very large files.

[/K]

For each source file that has its read-only attribute set, tells XCOPY to maintain the read-only attribute on the corresponding destination file.

[/L]

Displays a list of the files that XCOPY will copy. (No files are copied if you use /L.)

[/N]

Tells XCOPY to use 8.3 filenames in the destination folder. Use this switch if the destination folder is a FAT partition that doesn’t support long filenames.

[/O]

Tells XCOPY to also copy ownership and discretionary access control list data to the destination.

[/P]

Prompts you to confirm each file copy.

[/Q]

Tells XCOPY not to display messages during the copy.

[/R]

Includes read-only files in the copy.

[/S]

Tells XCOPY to also include the source folder’s subfolders in the copy.

[/E]

Tells XCOPY to include empty subfolders in the copy if you specify the /S or /T switch.

[/T]

Tells XCOPY to copy the source folder subfolder structure. (No files are copied, just the subfolders.)

[/U]

Copies only those source files that exist in the destination folder.

[/V]

Tells XCOPY to verify that each destination copy is identical to the original source file.

[/W]

Displays the message “Press any key to begin copying file(s)” before copying. You must press a key to launch the copy (or press Ctrl+C to cancel).

[/X]

Tells XCOPY to also copy file audit settings and system access control list data to the destination. (This switch implies /O.)

[/Y]

Tells XCOPY not to ask you whether you want to overwrite existing files in the destination.

[/-Y]

Tells XCOPY to ask you whether you want to overwrite existing files in the destination. Use this switch if you’ve set the %COPYCMD% environment variable to /Y, which suppresses overwrite prompts for XCOPY, COPY, and MOVE.

[/Z]

If you’re copying to a network destination, this switch tells XCOPY to restart to the copy if the network connection goes down during the operation.

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.

Table B.3 XCOPY Exit Codes

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.

Working with System Management Tools

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.

Table B.4 Windows 10’s Command-Line System Management Tools

Tool

Description

BCDEDIT

Displays or modifies the Boot Manager startup parameters

CHCP

Displays or changes the number of active console code pages

DATE

Displays or sets the system date

EVENTCREATE

Creates a custom event in an event log

REG

Adds, modifies, displays, and deletes Registry keys and settings

REGSVR32

Registers dynamic link library (DLL) files as command components in the Registry

SHUTDOWN

Shuts down or restarts Windows 10 or a remote computer

SYSTEMINFO

Displays a wide range of detailed configuration information about the computer

TIME

Displays or sets the system time

TYPEPERF

Monitors a performance counter

WHOAMI

Displays information about the current user, including the domain name (not applicable to Windows 10), computer name, username, security group membership, and security privileges

WMIC

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 Settings

In 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:

REG ADD

Adds new keys or settings to the Registry. You can also use this command to modify existing settings.

REG QUERY

Displays the current values of one or more settings in one or more keys.

REG COMPARE

Compares the values of two Registry keys or settings.

REG COPY

Copies Registry keys or settings to another part of the Registry.

REG DELETE

Deletes a key or setting.

REG EXPORT

Exports a key to a .reg file.

REG IMPORT

Imports the contents of a .reg file.

REG SAVE

Copies Registry keys or settings to a hive (.hiv) file.

REG RESTORE

Writes a hive file into an existing Registry key. The hive file must be created using REG SAVE.

REG LOAD

Loads a hive file into a new Registry key. The hive file must be created using REG SAVE.

REG UNLOAD

Unloads a hive file that was loaded using REG LOAD.

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]

KeyName

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.

/V ValueName

Specifies the Registry setting in KeyName that you want to view.

/VE

Tells REG to look for empty settings (that is, settings with a null value).

/C

Runs a case-sensitive query.

/E

Returns only exact matches.

/F data

Specifies the data that REG should match in the KeyName settings.

/K

Queries only key names, not settings.

/S

Tells REG to query the subkeys of KeyName.

/SE separator

Defines the separator to search for in REG_MULTI_SZ settings.

/T type

Specifies the setting type or types to search: REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_BINARY, or REG_NONE.

/Z

Tells REG to include the numeric equivalent of the setting type in the query results.

/reg:32

Tells REG to access KeyName using the 32-bit Registry view.

/reg:64

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 HKLMSoftwareMicrosoftWindows 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]

KeyName

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.

/V ValueName

Specifies the setting you want to add to KeyName.

/VE

Tells REG to add an empty setting.

/D data

Specifies the data that REG should use as the value for the new setting.

/F

Modifies an existing key or setting without prompting to confirm the change.

/S separator

Defines the separator to use between multiple instances of data in a new REG_MULTI_SZ setting.

/T type

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.

/reg:32

Tells REG to access KeyName using the 32-bit Registry view.

/reg:64

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 System

You 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"]

/R

Restarts the computer.

/G

Restarts the computer and, after you log on, restarts any applications that were running.

/S

Shuts down the computer.

/SG

Shuts down the computer and then restarts any registered applications on the next boot.

/L

Logs off the current user immediately.

/H

Puts the computer into hibernation, if the computer supports hibernation mode.

/I

Displays the Remote Shutdown dialog box, which enables you to specify many of the options provided by these switches.

/P

Turns off the local computer immediately (that is, without the usual warning interval).

/E

Enables you to document the reason for an unexpected shutdown.

/A

Cancels the pending restart or shutdown.

/O

Restarts the PC into the Recovery Environment. You must also include the /R switch.

/F

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.

/HYBRID

Shuts down the PC and prepares it for a fast restart. You must also include the /S switch.

/SOFT

Skips hardware initialization during the next reboot. You must also include the /S switch.

/FW

During the next restart, automatically boots the PC into its firmware setup utility. You must also include the /S switch.

/D [P|U:]major:minor]

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:

major

minor

Reason

0

0

Other

0

5

Other Failure: System Unresponsive

1

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.

/T seconds

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.

/C "comment"

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 Data

If 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]

/S computer

Specifies the name of the remote computer for which you want to view the system configuration.

/U [domain]username

Indicates the username and, optionally, the domain of the account under which you want to run the SYSTEMINFO command.

/P password

Specifies the password of the account you specified with /U.

/FO format

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.

/NH

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 Performance

In 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]

[counter1 counter2...]

Specifies the path of the performance counter to monitor. If you want to track multiple counters, separate each counter path with a space. If any path includes spaces, surround the path with quotation marks.

-CF file

Loads the counters from file, where file is a text file that lists the counter paths on separate lines.

-O file

Specifies the path and the name of the file that will store the performance data.

-F format

Specifies the format for the output file format given by the /O switch, where format is one of the following values:

csv—The output is displayed with each counter separated by a comma and each sample on its own line. This is the default output format.

tsv—The output is displayed with each counter separated by a tab and each sample on its own line.

bin—The output is displayed in binary format.

-SI interval

Specifies the time interval between samples. The interval parameter uses the form [mm:] ss. The default interval is 1 second.

-SC samples

Specifies the number of samples to collect. If you omit this switch, TYPEPERF samples continuously until you press Ctrl+C to cancel.

-Q [object]

Lists the available counters for object without instances.

-QX [object]

Lists the available counters for object with instances.

-CONFIG file

Specifies the pathname of the settings file that contains the TYPEPERF parameters you want to run.

-S computer

Specifies that the performance counters should be monitored on the PC named computer if no computer name is specified in the counter path.

-Y

Answers yes to any prompts generated by TYPEPERF.

The official syntax of a counter path looks like this:

[\Computer]Object([Parent/][Instance][#Index])Counter

Computer

The computer on which the counter is to be monitored. If you omit a computer name, TYPEPERF monitors the counter on the local computer.

Object

The performance object—such as Processor, Memory, or PhysicalDisk—that contains the counter.

Parent

The container instance of the specified Instance.

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.

Index

The index number of the specified Instance.

Counter

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 User

The 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]

/UPN

(Domains only) Returns the current user’s name using the user principal name (UPN) format.

/FQDN

(Domains only) Returns the current user’s name using the fully qualified domain name (FQDN) format.

/LOGONID

Returns the current user’s security identifier (SID).

/USER

Returns the current username using the computeruser format.

/GROUPS

Returns the groups of which the current user is a member.

/CLAIMS

(Domains only) Returns the current user’s claims.

/PRIV

Returns the current user’s privileges.

/ALL

Returns the current user’s SID, username, groups, and privileges.

/FO format

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.

/NH

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

Working with Users, Groups, and Shares

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 Users

You 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]]

username

Specifies the name of the user you want to add or work with. If you run NET USER with only the name of an existing user, the command displays the user’s account data.

password

Indicates the password you want to assign to the user. If you use *, Windows 10 prompts you for the password; if you use the /RANDOM switch, Windows 10 assigns a random password (containing eight characters, consisting of a random mix of letters, numbers, and symbols), and then displays the password on the console.

/ADD

Creates a new user account.

/DELETE

Deletes the specified user account.

options

These are optional switches you can append to the command:

/ACTIVE:{YES | NO}—Specifies whether the account is active or disabled.

/EXPIRES:{date | NEVER}—The date (expressed in the system’s Short Date format) on which the account expires.

/HOMEDIR:path—The home folder for the user, which should be a subfolder within %SystemDrive%Users (make sure that the folder exists).

/PASSWORDCHG:{YES | NO}—Specifies whether the user is allowed to change his password.

/PASSWORDREQ:{YES | NO}—Specifies whether the user is required to have a password.

/PROFILEPATH:path—The folder that contains the user’s profile.

/SCRIPTPATH:path—The folder that contains the user’s logon script.

/TIMES:{times | ALL}—Specifies the times that the user is allowed to log on to the system. Use single days or day ranges (for example, Sa or M-F). For times, use 24-hour notation or 12-hour notation with am or pm. Separate the day and time with a comma, and separate day/time combinations with semicolons. Here are some examples:

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 Groups

You 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}

group

Specifies the name of the security group with which you want to work.

name1 [name2 ...]

Specifies one or more usernames you want to add or delete, separated by spaces.

/ADD

Adds the user or users to the group.

/DELETE

Removes the user or users from the group.

NET USE: Mapping Folders

You 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]

drive

Specifies the drive letter (following by a colon) of the local drive to which you want the network folder mapped.

share

Indicates the network address of the folder.

password

Specifies the password required to connect to the shared folder (that is, the password associated with the username, specified next).

/USER:user

Specifies the username you want to use to connect to the shared folder.

/PERSISTENT:

Enables you to reconnect the mapped network drive the next time you log on when you add YES.

/DELETE

Deletes the existing mapping that’s associated with drive.

For example, the following command maps the shared folder \PAULSPCPaulWritingBooks to the Z: drive:

net use z: \paulspcpaulwritingooks /persistent:yes

Working with Network Troubleshooting Tools

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:

ARPThis 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.

NBTSTATThis utility displays the protocol statistics and the current TCP/IP connections using NBT (NetBIOS over TCP/IP). Enter nbtstat -? for the syntax.

NETSTATThis utility displays the protocol statistics and current TCP/IP connections. Enter the command netstat -? to display the syntax.

NSLOOKUPThis 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.)

PINGThis 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.”

ROUTEThis utility can be used to manipulate a network routing table (LMHOSTS). Enter route -? for the syntax.

TRACERTThis utility can check the route taken to a remote host. We also explain this valuable diagnostic command in Chapter 17.

IPCONFIGThis 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.131.238