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.

Image If you need a refresher on accessing and using the command line, see Chapter 30, “Command-Line and Automation Tools.”

Image

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


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

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]

Image
Image

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:


Image 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), and then click Command Prompt (Admin).


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

Image

When you run CHKNTFS with just a volume name, you see one of the following:

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

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

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


Image 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 QUERYvolume, 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:


Image 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), and then click Command Prompt (Admin).


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.


Image 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] [/H] [/I] [/K] [/L] [/M] [/O] [/T] [/U]
[/V] [/X]

Image

Image Note

To run the DEFRAG utility, you must use an administrator Command Prompt session. Press Windows Logo+X (or right-click the Start button), and then click Command Prompt (Admin).


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.

Image
Image

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

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:

Image

ATTRIB: Modifying File and Folder Attributes

A file’s attributes are special codes that indicate the status of the file. There are seven attributes you can work with:

Image Archive—When this attribute is turned on, it means the file has been modified since it was last backed up.

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

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

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

Image Not content indexed—When this attribute is set, the file’s contents will not be indexed for searching.

Image Read-only—When this attribute is turned on, it means the file can’t be modified or erased.

Image 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] [+R | -R] [+S | -S] [+U | -U]  [+X | -X]
filename [/S [/D] [/L]]

Image

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


Image 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 also 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

Image

For example, to find the string Xbox in a file named WishList.txt, you use the following command:

find "Xbox" WishList.txt


Image 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


Image 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_filename1 new_filename

Image

For example, the following command renames Budget 2015.xlsx to Budget 2016.xlsx:

ren "Budget 2015.xlsx" "Budget 2016.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 2015 somewhere in the filename. To rename all those files by changing 2015 to 2016, you would use the following command:

ren *2015* *2016*

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:

Image It copies files, but only if their names match those in the target directory.

Image It copies files, but only if their names don’t exist in the target directory.

Image 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

Image

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 have to 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]

Image

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] [/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]

Image
Image

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, 2013. You can do this by using the following command:

xcopy %userprofile%documents*.doc \serverusers\%Username% /d:08-23-2013

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

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.

Image

Table B.3 XCOPY Exit Codes

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


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

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

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

Image

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

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:

Image

We won’t go through all of 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 SettingName | /VE] [/C] [/D] [/E] [/F data] [/K | [/S]
   [/SE separator] [/T type] [/Z]

Image

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 SettingName | /VE] [/D data] [/F | [/S separator] [/T type]

Image

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"

Windows 10 responds with the following prompt:

Value CurrentProject exists, overwrite (Yes/No)?


Image Tip

To avoid being prompted when changing existing settings, add the /F switch to the REG ADD command.


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] | [/L] | [/H] | [/I] | [/P] | [/E] | [/A] | [/O]] [/F |
   [/HYBRID] [/T seconds] [/D [P:]xx:yy] [/M \ComputerName] [/C "comment"]

Image
Image
Image

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:

Image The operating system name, version, and configuration type

Image The registered owner and organization

Image The original install date

Image The system boot time

Image The computer manufacturer, model, and system type

Image The system processors

Image The BIOS version

Image The total and available physical memory

Image The paging file’s maximum size, available size, in-use value, and location

Image The installed hotfixes

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

Image

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.

Image For the details on the Performance Monitor utility, seeUsing the Performance Monitor,” p. 542.

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]

Image

The official syntax of a counter path looks like this:

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

Image

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 need to 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]

Image

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

Image

Note, too, that if you execute NET USER without any parameters, it displays a list of the local user accounts.


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



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

Image

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]

Image

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:

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

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

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

Image 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 more detail in the next section.

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

Image TRACERT—This utility can check the route taken to a remote host. We explain this valuable diagnostic command in more detail later.

Image IPCONFIG—This utility displays the current TCP/IP network configuration. If you run the command ipconfig without any 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, as shown here:

Windows IP Configuration
 Host Name . . . . . . . . . . . . : MediaPC
 Primary Dns Suffix  . . . . . . . :
 Node Type . . . . . . . . . . . . : Hybrid
 IP Routing Enabled. . . . . . . . : No
 WINS Proxy Enabled. . . . . . . . : No
 DNS Suffix Search List. . . . . . : phub.net.cable.rogers.com

Ethernet adapter Local Area Connection:

 Connection-specific DNS Suffix  . : phub.net.cable.rogers.com
 Description . . . . . . . . . . . : Atheros L1 Gigabit Ethernet 10/100/
1000Base-T Controller
 Physical Address. . . . . . . . . : 00-1E-8C-7D-97-3A
 DHCP Enabled. . . . . . . . . . . : Yes
 Autoconfiguration Enabled . . . . : Yes
 Link-local IPv6 Address . . . . . : fe80::452f:6db7:eaf2:3112%11(Preferred)
 IPv4 Address. . . . . . . . . . . : 192.168.0.84(Preferred)
 Subnet Mask . . . . . . . . . . . : 255.255.0.0
 Lease Obtained. . . . . . . . . . : Monday, October 24, 2016 10:38:42 AM
 Lease Expires . . . . . . . . . . : Tuesday, October 25, 2016 2:07:16 PM
 Default Gateway . . . . . . . . . : 192.168.1.1
 DHCP Server . . . . . . . . . . . : 192.168.1.1
 DHCPv6 IAID . . . . . . . . . . . : 234888844
 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-11-52-C4-05-00-1E-8C-7D-97-3A
 DNS Servers . . . . . . . . . . . : 192.168.1.1
 NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter isatap.phub.net.cable.rogers.com:

 Media State . . . . . . . . . . . : Media disconnected
 Connection-specific DNS Suffix  . : phub.net.cable.rogers.com
 Description . . . . . . . . . . . : Microsoft ISATAP Adapter
 Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
 DHCP Enabled. . . . . . . . . . . : No
 Autoconfiguration Enabled . . . . : Yes

Tunnel adapter Teredo Tunneling Pseudo-Interface:

 Connection-specific DNS Suffix  . :
 Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
 Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
 DHCP Enabled. . . . . . . . . . . : No
 Autoconfiguration Enabled . . . . : Yes
 IPv6 Address. . . . . . . . . . . : 2001:0:4137:9e50:3032:38c1:3f57:ffab
(Preferred)
 Link-local IPv6 Address . . . . . : fe80::3032:38c1:3f57:ffab%13(Preferred)
 Default Gateway . . . . . . . . . : ::
 NetBIOS over Tcpip. . . . . . . . : Disabled

Tunnel adapter Reusable ISATAP Interface {D767BCA8-D27E-404C-9A50-CD680EF507C0}:

 Media State . . . . . . . . . . . : Media disconnected
 Connection-specific DNS Suffix  . :
 Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
 Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
 DHCP Enabled. . . . . . . . . . . : No
 Autoconfiguration Enabled . . . . : Yes

Here’s a basic procedure you can run through to troubleshoot networking problems using the command-line tools:

1. Release the current DHCP lease by running the following command:

ipconfig /release

2. Renew the DHCP lease by running the following command:

ipconfig /renew


Image Note

A DHCP lease is a guarantee that the Dynamic Host Configuration Protocol (DHCP) client computer will have the IP address supplied by the DHCP server for a specified period of time. To avoid lease expiration, the DHCP client usually sends a request—a DHCPREQUEST message—for lease renewal to the original DHCP server after 50% of the lease time has expired. If 87.5% of its lease time has expired, the DHCP client sends a lease renewal request to all available DHCP servers.


3. Flush the ARP cache. The ARP handles the conversion of an IP address to a physical address of a network adapter. (To see the physical address of your adapter, open the connection’s Status dialog box, display the Support tab, and click Details.) To improve performance, Windows 10 stores resolved addresses in the ARP cache for a short time. Some networking problems are caused by ARP cache entries that are obsolete or incomplete. The cache is normally flushed regularly, but to force a flush, run the following command:

arp -d


Image Tip

To see the contents of the ARP cache, run the following command:

arp -a

You’ll see output similar to the following:

Interface: 192.168.1.101 --- 0x2
  Internet Address        Physical  Address      Type
  192.168.1.1           00-12-17-8c-48-88     dynamic
  192.168.1.100         00-11-24-1a-7a-fc     dynamic
  192.168.1.103         00-11-11-be-c7-78     dynamic


4. Flush the NetBIOS name cache. NetBIOS handles the conversion between the network names of computers and their IP addresses. To improve performance, Windows 10 stores resolved names in the NetBIOS name cache. To solve problems caused by NetBIOS name cache entries that are obsolete or bad, this step clears the cache. Run the following command:

nbtstat -r

5. Reregister the computer with the network’s WINS server. That is, you ask the WINS server to release the computer’s NetBIOS names that are registered with the server and then reregister them. This capability is useful if you’re having problems connecting to other computers using their network names. Just run the following command:

nbtstat -rr

6. Flush the DNS cache. DNS handles the conversion of domain names to IP addresses. To improve performance, Windows 10 stores resolved domain names in the DNS cache. To solve problems caused by DNS cache entries that are obsolete or bad, clear the cache by running the following command:

ipconfig /flushdns

7. Reregister the computer with the DNS server. This capability is useful if you’re having trouble resolving domain names or if you’re having trouble with a dynamic DNS server. Just run the following command:

ipconfig /registerdns

PING: Checking Connectivity

As you might know, a submarine can detect a nearby object by using sonar to send out a sound wave and then seeing whether the wave is reflected. This is called pinging an object.

Windows 10 has a PING command that performs a similar function. PING sends out a special type of IP packet—called an Internet Control Message Protocol (ICMP) echo packet—to a remote location. This packet requests that the remote location send back a response packet. PING then tells you whether the response was received. In this way, you can check your network configuration to see whether your computer can connect with a remote host.

To use PING, press Windows Logo+X (or right-click the Start button) and click Command Prompt (Admin). Here’s a simplified version of the PING syntax:

ping [-t] [-n count] target_name

Image

Here’s an example that uses PING on the Google.com domain:

C:UsersPaul>ping google.com
Pinging google.com [64.233.187.99] with 32 bytes of data:
Reply from 64.233.187.99: bytes=32 time=43ms TTL=240
Reply from 64.233.187.99: bytes=32 time=42ms TTL=239
Reply from 64.233.187.99: bytes=32 time=43ms TTL=239
Reply from 64.233.187.99: bytes=32 time=42ms TTL=240

Ping statistics for 64.233.187.99:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),A
Approximate round trip times in milli-seconds:
    Minimum = 42ms, Maximum = 43ms, Average = 42ms

Here you see that each echo packet received a reply. If you can’t connect to the remote host, PING returns a Request timed out message for each packet.

If you can’t connect to a remote host, here are some notes on using PING to troubleshoot problems:

Image First, check to see whether you can use PING successfully on the loopback address:

ping 127.0.0.1.

The only reason this PING would fail is if your computer doesn’t have the Internet Protocol installed. However, all Windows 10 machines have IP installed, and the option to uninstall it is disabled, so pinging the loopback address will almost certainly work. The only reason to include it in your troubleshooting is that if it doesn’t work, it means you have a serious problem with your machine. Either revert to a working configuration, reinstall Windows 10, or take your machine to a computer repair professional.

Image Try using PING on your computer’s IP address. (If you’re using DHCP, run the IPCONFIG utility to get your current IP address.) If you don’t get a successful echo, your NIC may not be inserted properly or the device drivers may not be installed.

Image Now PING another computer on your network. If PING fails, check your cable or wireless connections.

Image The next test you should run is on your default gateway (that is, your router). If you can’t successfully PING the router’s internal IP address, you won’t be able to access remote Internet sites. In this case, check the IP address you entered for the gateway, check the cable connections, and make sure the router is turned on. You may need to power cycle the router.

Image If you get this far, try using PING on the remote host you’re trying to contact. If you’re unsuccessful, check to make sure you’re using the correct IP address for the host. Try power cycling your broadband modem.

TRACERT: Tracking Packets

If you can’t PING a remote host, your echo packets might be getting held up along the way. To find out, you can use the TRACERT (trace route) command:

tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name

Image

TRACERT operates by sending ICMP echo packets with varying TTL values. Recall that TTL places a limit on the number of hops that a packet can take. Each host along the packet’s route decrements the TTL value until, when the TTL value is 0, the packet is discarded (assuming that it hasn’t reached its destination by then).

In TRACERT, the ICMP packets specify that whichever host decrements the echo packet to 0 should send back a response. So, the first packet has a TTL value of 1, the second has a TTL value of 2, and so on. TRACERT keeps sending packets with incrementally higher TTL values until either a response is received from the remote host or a packet receives no response. Here’s an example of a TRACERT command in action:

C:>tracert google.com
Tracing route to google.com [216.239.57.99]
over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  192.168.1.1
  2     8 ms     8 ms     8 ms  64.230.197.178
  3     6 ms     6 ms     6 ms  64.230.221.201
  4     6 ms     6 ms     6 ms  64.230.234.249
  5     8 ms     6 ms     7 ms  64.230.233.93
  6    17 ms    17 ms    16 ms  core1-chicago23-pos0-0.in.bellnexxia.net
   [206.108.103.130]
  7    17 ms    17 ms    17 ms  bx2-chicago23-pos11-0.in.bellnexxia.net
   [206.108.103.138]
  8    17 ms    17 ms    17 ms  so-4-3-3.cr1.ord2.us.above.net [208.184.233.185]
  9    18 ms    17 ms    18 ms  so-0-0-0.cr2.ord2.us.above.net [64.125.29.186]
  10    36 ms    36 ms    36 ms  so-5-2-0.cr1.dca2.us.above.net [64.125.30.225]
  11    47 ms    46 ms    46 ms  so-4-1-0.mpr2.atl6.us.above.net [64.125.29.41]
  12    48 ms    48 ms    48 ms  64.124.229.173.google.com [64.124.229.173]
  13    48 ms    48 ms    48 ms  216.239.48.23
  14    49 ms    49 ms    49 ms  216.239.46.44
  15   100 ms   100 ms   100 ms  216.239.47.129
  16    99 ms    99 ms    99 ms  216.239.49.250
  17    99 ms    99 ms    99 ms  66.249.95.65
  18    99 ms    99 ms    99 ms  66.249.94.27
      102 ms   101 ms   101 ms  216.239.49.97
  20    99 ms   100 ms    99 ms  216.239.57.99
Trace complete.

The first column is the hop number (that is, the TTL value set in the packet). Notice that, in my case, it took 20 hops to get to Google.com. The next three columns contain round-trip times for an attempt to reach the destination with that TTL value. (Asterisks indicate that the attempt timed out.) The last column contains the hostname (if it was resolved) and the IP address of the responding system.

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

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