Chapter 5

Command Prompt Procedures

EXAM OBJECTIVES

Identifying the fundamentals of using command line utilities to manage Windows

Using command line tools to manage directories and files

In this chapter, you take a look at several command prompt utilities and a few graphical utilities. Even in the age of Windows, statements that can be issued from a command prompt are still required knowledge for support professionals. This knowledge will help you automate processes — such as batch files — and solve problems when the graphical operating system is not functioning. After reading this chapter, you should have a good understanding of many of the basic commands that are available from the command prompt.

As an added benefit, you find out how to build a basic batch file with some controls in it. I put this information at the end of the chapter because you won’t be tested directly on that knowledge, but it will sure come in handy on the job.

As an A+ Certified Professional, you will want to use the full range of tools available to you. This chapter introduces you to many of the command line tools that allow you to quickly diagnose and repair problems with operating systems.

remember The A+ Exam objectives call for testing on command line tools, which should be limited to the common tools from the exam objectives, which have been listed in this book. To review all possible command line tools for Windows, go to http://technet.microsoft.com/en-us/library/cc754340.aspx or do a web search for Windows Command line reference A-Z.

Using command.com and cmd.exe

Many of the really useful utilities in Windows are command line–based. Windows 7 (32–bit) and earlier 32–bit OSes give you two options for running command line utilities: command.com and cmd.exe.

Windows NT–based OSes, such as Windows Vista through to Windows 8.1, use cmd.exe as the basic command line interpreter for issuing commands. When using cmd.exe, you are using a Windows 32-bit application from the point of view of memory management and application stability. command.com still exists on these OSes, but it exists for backward compatibility for older applications, and you will only find it on 32-bit systems. As a command line interpreter, there are certain commands which are built into it, and other commands which are read from the Windows directory. This is why you will not find copy on your computer, but you will find xcopy.exe; copy is command which is internal to the interpreter, while xcopy.exe is a command which is external to the interpreter, and therefore found in the Windows directory.

Typically, when you want to use a command prompt within Windows, you should run cmd.exe by choosing Start ⇒ Run, typing cmd.exe, and clicking OK. cmd.exe can also be found from the Start menu under All Programs ⇒ Accessories ⇒ Command Prompt. This runs as a 32-bit or 64-bit Windows application (depending on the version of Windows you are running) and thereby can spawn other applications or support standard memory management. Each copy of cmd.exe that you execute appears on the process list in Task Manager. If you run cmd.exe, the first two lines tell you what executed. Here is an example of what Windows 7 shows:

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

On 32-bit computers, command.com on the other hand, is a 16-bit MS-DOS application. It loads a simulated 16-bit environment in the form of ntvdm.exe (NT Virtual DOS Machine; NTVDM). You will see ntvdm.exe listed on the Process tab of Task Manager. The first two lines listed in this window are

Microsoft(R) Windows DOS
(C)Copyright Microsoft Corp 1990-2001.

You will notice that, in this case, you are running DOS and Windows 7 (Windows Version 6.1). You will also notice, if you are running an OS prior to Windows Vista, that your long filenames are no longer supported. If you use the command prompt to launch other 16-bit Windows applications, they will be launched within the NTVDM that is executing. The NTVDM is the environment that all 16-bit MS-DOS applications and 16-bit Windows applications run in. For more information about supporting these applications, refer to Book 6, Chapter 2.

cmd.exe is used when running all other applications. As I mention earlier, it is a 32-bit command prompt with a number of enhancements, including

  • The ability to run 16-bit and 32-bit command line utilities
  • The ability to run POSIX (Portable Operating System Interface for Unix) and OS applications
  • Built-in command history support for saving and executing commands

remember 32-bit versions of Windows use cmd.exe as the main command line interface and provide command.com for backward compatibility with 16-bit MS-DOS and Windows applications. Remember that command.com is not supported on 64-bit Windows operating systems, and the default version of cmd.exe is a 64-bit application. Even on a 64-bit version of Windows, Microsoft does provide a 32-bit version of cmd.exe for backward compatibility with 32-bit applications.

When you are using any of the command prompt interfaces, you can type exit to leave the interface. Remember that the command prompt session may be nested, and exit will only leave the current session or level.

Executing Your Privileges

For security reasons, it is not recommended that you log in and run applications using an account that has full administrative rights; rather you should use an account that has normal user rights for all day-to-day operations. There will be times, however, when you need to have elevated permissions to accomplish a task. To aid you in this process Microsoft provided a special command: runas.

runas

The runas command is used to do just that: run a command as someone else. In most cases you will use it to run a command as a user with administrative rights, but sometimes for testing, you may want to use it to run a command as a user with fewer rights than your normal user.

The basic options required to use the runas command are summarized in Table 5-1.

TABLE 5-1 Switches Used with the runas Command

Switch

Description

/noprofile

This switch prevents the profile of the specified user from being loaded. By bypassing the profile, the command can directly execute, but it may fail if information from the profile is required.

/profile

/profile forces the profile or the specified user to be loaded. It is the default option.

/env

Similar to the /noprofile option, the /env option retains the current command environment rather than reloading it as the user.

/netonly

This switch will skip loading the local profile as the credentials are to be used to authenticate to a remote system.

/savecred

This option is used to continue using previously saved credentials.

/smartcard

This option uses credentials from a smartcard.

/user

The /user option specifies the user credentials to use for running the specified command in the form user@domain or domain\user.

/showtrustlevels

This switch displays the trust levels that can be used for the command.

/trustlevel

This switch specifies a trust level to use for the command.

program

The name of the program and any command line option that are to be used. If any spaces occur, the entire command is required to be in quotes. If quotes are needed by the command inside of quotes, inner quotes should be proceeded by the escape character \.

To run the command regedit.exe as the local Administrator account, the command would be similar to the following:

runas /profile /user:Contoso\Administrator "reg.exe import \"C:\MyRegFile.reg\""

If you prefer to not use the command line, you can also access this functionality for applications by selecting the application, pressing the Shift key, right-clicking, and then selecting Run as Different User. This action will present you with a logon dialog box that will be tied to the application.

Using commands with privilege

Even when you are logged into an account that has administrator privilege, you still may not be able to run certain commands. For example, if you are going to use a command that has potential to do damage or make the computer inoperable, then you will likely need to have privilege. To get the elevated privileges you need, run the Administrator Command Prompt. The Administrator Command Prompt is there to prevent accidental execution of dangerous commands. Think of it as User Access Control (UAC) for the command prompt.

To run the Administrator Command Prompt, locate a shortcut to the command prompt by selecting Start, type cmd, right-click the shortcut, and select Run as Administrator. With Windows 7 and newer OSes, you can right-click on a running command prompt in the Taskbar, right-click command prompt in the menu, and then select Run as Administrator.

The following commands require that you have administrative privilege and be using the Administrative Command Prompt in order to properly run them:

  • chkdsk.exe
  • defrag.exe
  • diskpart (does not require administrative command prompt, but does require a UAC prompt if not using an administrative prompt)
  • shutdown

Each of these commands is covered in detail later in this chapter. Remember, when you run a command and do not get the expected output, it may be that you do not have the rights to see what is missing.

Managing Directories

All files that are saved to disk are stored in a hierarchical directory structure. All the files could be placed at the top of this structure, but it would be disorganized, and therefore poorly managed. Also, most top-level directories, or root directories, can hold a limited number of files. This directory structure can hold as many nested sub-directories as you want. The commands discussed in the following sections allow you to get listings of files as well as create and delete directories on your disk.

remember All command line tools in this section have not changed substantially since MS-DOS, but some have a few more options than they used to have.

dir

The first command that you will see is the directory command (dir). This command is used to get a listing of the files that are in a directory on your disk. Using dir by itself gives you the listing of your current directory. The current directory is usually listed in the command prompt, like this:

C:\WINDOWS>_

The dir command is very useful and has several options, discussed later in this section. First, though, you need a firm grasp of wildcards, relative paths, and absolute paths.

Wildcards

Two wildcards can be used to modify what results you receive: * and ?. These can be used multiple times in different combinations in the same command to filter the results.

The * wildcard represents one or more characters. Here is an example of using the * wildcard to retrieve a list of files that match a certain pattern. The command

dir WIN*.*XE

returns the following:

WindowsAnytimeUpgradeResults.exe
wininit.exe
winload.exe
winlogon.exe
winresume.exe
winrs.exe
winrshost.exe
WinSAT.exe
winver.exe

The results include all files that start with win and end with xe, with any number of characters in between — even zero. These wildcards are also useful when used in conjunction with copy commands, which I discuss later in the chapter.

The ? wildcard character works a little different than * because ? represents one or zero characters. Here is an example of ? in action, as it looks for all files that were created on the fifth of any month after Jan 01, 2000, given that all the filenames match their dates using eight-character numeric dates with the pattern of mmddyyyy.txt. The command

dir ??052???.TXT

would return the following list of files:

01052000.TXT
05052000.TXT
10052000.TXT
11052000.TXT
12052000.TXT
04052002.TXT
12052003.TXT
06052008.TXT

The ? in the command doesn’t return any files that have more than two characters before the 05 and doesn’t return any more than three characters after the 2 in the dir statement.

Relative paths and absolute paths

When you use dir, you are given a directory listing for your current directory. To see the listing for a different directory, Table 5-2 provides several options for choosing a different directory. All the command examples in the table use this directory structure:

c:\parent_dir\child_dir\grandchild_dir

with the current directory set to c:\parent_dir\child_dir.

TABLE 5-2 Ways to Specify Directory Paths

Command

Directory Result

dir

Returns the listing for the current directory

c:\parent_dir\child_dir.

dir c:

Returns the listing for the current directory on the C: drive

c:\parent_dir\child_dir.

dir c:\parent_dir

Returns the listing for

c:\parent_dir.

dir \

Returns the listing for the root of the current drive

c:\.

dir ..

Returns the listing for the parent directory of the current directory

c:\parent_dir.

dir ..\..

Returns the listing of the parent directory of the parent directory of the current directory

c:\.

dir ..\child_dir

Returns the listing of a directory named child_dir, which is a child of the parent directory

c:\parent_dir\child_dir.

dir grandchild_dir

Returns the listing of a child directory named

grandchild_dirc:\parent_dir\child_dir\grandchild_dir.

Whenever a full path is specified, starting with the drive letter, it is referred to as an absolute path. If you do not specify the full path, you are using a relative path. Care should always be taken when using relative paths with commands. Look, for example, at the following code sample:

dir sub_dir
del *.*

In this example, a directory (dir) listing is taken of a sub-directory (sub_dir), and the following delete (del) command was working on the entire contents of the current directory, not the directory listing which was just retrieved. This is an easy mistake to make. When working with relative paths, double period (..) notation refers to a parent directory, and single period (.) notation refers to the current directory.

Most programs and commands can have their actions modified by providing options on the command line. These options are usually represented by one or more letters and are introduced to the command with either / or -. The - character is usually used with commands that come from (converted from) the Unix OS, but most MS-DOS programs have implemented /. These options are referred to as switches. dir /on /s is an example of the dir command using switches.

Table 5-3 summarizes some of the most important switches for the dir command.

TABLE 5-3 Switches for dir

Switch

Description

/ax

The /a switch is short for attributes. This switch provides a listing of files that have matching attributes. This switch must be used in conjunction with an additional letter to provide results. Five letters may be used: (d)irectory, (a)rchive, (h)idden, (s)ystem, and (r)ead-only. Using a minus sign with one of these five letters reverses the listing: For example, /a-d shows you things that are not directories.

/b

The /b command displays a bare listing. A bare listing does not include a separate section in the output that tells you the directory that you are working with, but rather displays a single-line listing, like this output from these example commands:

dir /b /s c:\windows\system32\bcd*.exe

c:\windows\system32\bcdboot.exe

c:\windows\system32\bcdedit.exe

dir /b c:\windows\system32\bcd*.exe

bcdboot.exe

bcdedit.exe

/ox

The /o switch is short for order by. This switch is similar to /a in that /o also requires an additional letter to tell it how to order or sort. The options available for sorting are (n)ame, (s)ize, (e)xtension, (a)ccessed date (earliest first), and (d)ate modified (earliest first). Using a minus sign (for example, /o-d) reverses the order. If you use the letter g after the o (for example, /ogd), directories will be grouped at the top of the list rather than mixed in.

/p

This switch pauses the screen after each full screen of text and waits for a key to be pressed. If you do not use this option, you can use the pipe-more command, which looks like this

dir c:\windows\*.exe | more.

/s

This switch includes listings for each sub-directory under the directory listing.

/w

This switch displays text in a wide listing. It enables more text to be displayed onscreen by using multiple columns.

/x

This switch is used on Windows Vista and newer computers to display short and long filenames.

tip In this chapter, you see many switches for each of the command line tools, but these are not all of the possible switches. To see the complete list, type the command with a /? after it, like this:

dir /?

If you want to use the same set of switches each time you execute the dir command, use the dircmd environment variable. This variable can be set in the autoexec.bat file or at a command prompt, like this:

set dircmd=/on /w

Now, every time you use dir, you will get output that looks like this:

Volume in drive C is DRIVE_C
Volume Serial Number is FC26-B8E0

Directory of C:\Windows\panther

[.] [..] cbs.log
Contents0.dir Contents1.dir DDACLSys.log
diagerr.xml diagwrn.xml [FastCleanup]
MainQueueOnline0.que MainQueueOnline1.que setup.etl
[setup.exe] setupact.log setuperr.log
setupinfo [UnattendGC]
12 File(s) 1,002,964 bytes
5 Dir(s) 24,540,774,400 bytes free

tip Note that the list is presented in wide format and sorted by name.

If you are using Windows and you want the setting of the dircmd variable to be saved, add the variable by using the Environment Variables settings in the System Control Panel, which you can get to by choosing Properties when you right-click Computer (or This PC for Windows 8.1 or newer users) to open the System Properties dialog box; then click the Advanced System Settings link and the Environment Variables button.

md

md, or mkdir, is used to create directories; there is no difference between the two commands other than their spelling.

The directory created will be in the current directory unless you provide an alternative path to the command, like this:

md "c:\temp\my new directory"

cd

cd, or chdir, is used to change the current directory for a drive to another directory. The drive need not be your current drive; this command can set a current directory on another drive. For example, if your current drive is C:, you could still use cd d:\my_dir_on_d to change the current directory for the D: drive. You will not see a difference onscreen, but if you change to the D: drive by using d:, you will see that the current directory is set to d:\my_dir_on_d. The current directory is important when you want to use other file operation commands, such as copy. If you only specify the drive that you want to work with, you will be working with the current directory on that drive. Take a look at this example:

D:\somedirectory\>c:
C:\Documents and Settings\ed\>cd \
C:\>mkdir d:\old_configs
C:\>cd d:\old_configs
C:\>copy a*.bat d:
C:\>copy c:\c*.sys d:\old_configs

The first line changes your current drive to C:. The second changes to the root directory of the current drive (c:\). The third creates a new directory on the D: drive, and the fourth line sets old_configs as the current directory on the D: drive. You will see the copy command in the upcoming section “copy,” but the fifth line copies all files in the current directory that start with a and end with .bat to the current directory on the D: drive (currently old_configs). The last line copies all files from c:\ that start with c and end with .sys to d:\old_configs. Lines 5 and 6 copy files from the same directory (c:\); the relative path is used in line 5, and the absolute path is used in line 6. The destination directory in line 6 is also absolute, and the relative path or current directory is used in line 5. In both statements (lines 5 and 6), the same directories are used as the source and destination directories.

warning Relative paths can save on typing, but they can also cause errors if you are not careful.

rd

rd, or rmdir, is used to remove or delete directories from your drive. Two rules are imposed on you: Before you delete a directory

  • The directory must be empty.
  • It cannot be the current directory.

You can empty a directory by using the del command to delete the files. To remove a directory, though, just specify its location after the rd command:

rd c:\remove_me

If you are using Windows Vista or a newer Windows OS, you can use an optional switch — /s — that will automatically delete sub-directories and files, overriding the first rule.

Copying and Moving Files

Doesn’t it seem like when you finally get things organized, it’s time to start all over again? When organizing and backing up files, you will often be required to copy or move files to new locations, either in another directory or on another disk. The following sections provide an overview of the commands that help you with these tasks.

copy

The copy command expects you to give at least the name of the file you would like to copy. If you provide only one filename, the selected file is copied into the current directory. If you provide a source filename and a destination directory by using a command like

copy c:\source\myfile.txt c:\destination

the file will be copied into the destination directory. You can also rename files while you are copying them by using a command like this:

copy c:\source\*.bat c:\destination\*.old

The preceding command would copy all files with an extension of .bat from the source directory and rename them with an .old extension in the destination directory.

If you are about to overwrite an existing file, you will be prompted to confirm the operation. This can be suppressed if you use /Y at the end of your copy command. /Y answers “yes” to the copy command’s “confirm overwrite?” question. If you want to consistently overwrite destination files, you can set the copycmd environment variable to /Y in the same manner that you set the dircmd variable in the “dir” section, earlier in this chapter.

xcopy

Many times, you have to copy entire directory structures from one location to another. If you were to do this with the copy command, you would first have to create all the destination directories by using the md command. When using the xcopy command, though, you can perform this task in a minimal amount of time. To copy an existing directory named source to a new directory named destination, you would issue the following command:

xcopy c:\source\*.* c:\destination\*.*

To copy all the sub-directories as well, use

xcopy c:\source\*.* c:\destination\*.* /s

To also include empty directories, add the /e (empty) switch to the end of the command. To include just files with the archive attribute set, add the /a (archive) switch.

Like the copy command, adding /Y will overwrite files without asking for confirmation. The /Y tells the command to answer “yes” to all overwrite prompts.

robocopy.exe

The robocopy.exe command is a turbocharged version of the xcopy command used to copy files and directories between locations. As with xcopy, you need to specify at least a source directory and a destination directory. To copy an existing directory named source to a new directory named destination, you would issue the following command

robocopy.exe c:\source c:\destination

The robocopy.exe command supports a wide variety of options — and some of the most common are listed in Table 5-4 — but if you are interested in this useful command, explore all of the options using robocopy.exe /?.

TABLE 5-4 Switches for robocopy.exe

Switch

Description

/e

The /e switch copies all source directories to the destination location, including empty directories.

/purge

The /purge option deletes destination directories that no longer exist in the source directory. This may be the case if you are running the robocopy.exe command a second time, after making changes to the source directory.

/z

The /z command copies the files in restartable mode, which is useful if copying large files over a slow network. If the file copy is interrupted, it can pick up in the middle of the file it was working on, rather than starting at the beginning of the file.

/b

This switch copies the files in backup mode, which may be necessary if you have files that open by users, and robocopy.exe cannot get a lock on the file. Backup mode allows for files to copied without putting locks on the files.

/copyall

This switch copies all file properties, including data, attributes, time stamps, NTFS permissions, owner information, and auditing information.

/mir

The /mir switch is the same as running robocopy.exe with both the /e and /purge switches.

/mot:m

This option monitors the source directory, and will rerun the robocopy.exe command again if any changes are found within the number of minutes defined by the m.

/r:n

The option should be a mandatory option; it specifies how many times robocopy.exe should attempt to copy failed files. Specify the number of attempts with the n. The default is one million attempts.

/w:n

The /w switch works with /r, as it is the time in seconds (n) to wait between attempts to copy the failed files. The default is 30 seconds.

/v

To see a list of all of the files that are copied, use the /v switch.

/log:file

This switch creates a log file, listing all of the files that are copied, and saves it in the file specification that follows the colon.

When robocopy.exe has completed its operation, it will display a summary. Here is an example of robocopy.exe copying a small temp directory with a sub-directory to a new location, temp2.

C:\>robocopy.exe /mir /v c:\temp c:\temp2

-----------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows

-----------------------------------------------------------------------------

Started : Fri Apr 06 20:57:25 2012

Source : c:\temp\
Dest : c:\temp2\

Files : *.*

Options : *.* /V /S /E /COPY:DAT /PURGE /MIR /R:1000000 /W:30

-----------------------------------------------------------------------------

New Dir 1 c:\temp\
100% New File 24 autoexec.old
New Dir 1 c:\temp\sub\
100% New File 24 autoexec.bat

-----------------------------------------------------------------------------

Total Copied Skipped Mismatch FAILED Extras
Dirs : 2 2 0 0 0 0
Files : 2 2 0 0 0 0
Bytes : 48 48 0 0 0 0
Times : 0:00:00 0:00:00 0:00:00 0:00:00

Ended : Fri Apr 06 20:57:25 2012

From the output, you should see that two directories were created and two files were copied. Two of the biggest advantages of robocopy.exe are the ability to refresh a previously copied directory by only updating changed files and to resume failed copy operations.

move

The move command moves files from one directory to another. It is also used to rename directories. To use the move command, you have to specify the name of the files you want to move and then specify the destination directory, like this:

move c:\source\source_file.txt c:\destination\

This example moves the file source_file.txt into the directory c:\destination\. If the destination directory does not exist, you will see an error message.

To rename the directory c:\source, you need to use

move c:\source destination

del

To delete or remove files or directories, you can use del or erase. Like earlier examples, these two commands are synonymous. If you want to delete multiple files, you have to use the * and ? wildcards. (Read about wildcards earlier in this chapter.) Windows allows you to delete directories with this command, and you can use /S to delete files from all sub-directories as well. If you do not want to be prompted to confirm deletions, use /Q for quiet. To select files to delete based on their attributes, use /A in the same manner as the dir command.

warning It is very easy to unintentionally delete files (or delete the wrong files) when working with relative paths. When possible, use full pathnames to avoid mistakes.

ren

The ren command is used to rename files and directories. Similar to many of the commands that you have looked at, you specify the source name and a new name for the file or directory.

Performing Diagnostics and Tuning Performance

At the command prompt, a few commands can be used to optimize and diagnose your computer. defrag.exe can be used to optimize your hard drive, and chkdsk.exe can be used to check your disk for errors.

The command prompt versions of the defrag.exe and chkdsk.exe utilities have now been replaced by Windows versions, but these commands are great if you are creating scripts or batch files to perform these actions.

defrag.exe

The purpose of the defrag.exe utility is to fix speed and performance problems with hard drives. As files are written to and then deleted from a disk, they leave holes or blank areas scattered around your drive. When you write files to a disk, they always write to the largest open spaces that are available to them. There will be times when the largest area is not large enough for the entire file, and the file will have to be split into pieces. These fragmented files are slower to access because the disk head has to keep moving to a new location on the drive. To defragment the files on your hard drive, use Computer Management in Windows, or defrag from the command line. To assist users with scripting solutions to use most tools, or to allow them to run the commands through command line only sessions on a server, Microsoft provides command line access to most Windows-based utilities.

technicalstuff With the popularity of solid state drives (SSD) you do not need to worry about defrag. Defragmenting a drive eliminates a drive head seek delay, but SSDs do not have heads that need to move.

In either case, you are using the defragmentation utility from Executive Software, and you have the option to analyze only or to force defragmentation when disk space is low.

tip For more information about using Computer Management in Windows, see Book 6, Chapter 4.

remember defrag.exe disappeared from the Windows OS when Windows 2000 created a graphical tool, but it has returned to Windows and is found in Windows Vista and newer Windows operating systems.

chkdsk.exe

chkdsk.exe serves an important purpose within the Windows operating system. Its job is to check

  • The directory structure and directory entries for corruption
  • The disk for worn-out areas

Its purpose is to reduce the chance of data loss by catching corruption early and by fixing small problems before they become larger.

tip For more information about chkdsk.exe, read Book 6, Chapter 4.

shutdown.exe

shutdown.exe is listed here as a diagnostic tool as it allows for the shutdown of the local computer or of a remote computer. This is useful when you want to perform a reboot at the end of a batch file or need to remotely reboot a computer which you have been performing maintenance or troubleshooting on. Table 5-5 summarizes the main options for the shutdown.exe command.

TABLE 5-5 Switches for shutdown.exe

Switch

Description

/?

This option displays help information for the command.

/i

This option displays the GUI window to let you execute the command with various options, but in a graphical manner.

/l

This option logs the current user off, but does not shut down the computer.

/s

/s shuts down the computer.

/r

/r shuts down and restarts the computer.

/g

/g shuts down and restarts the computer, and then restarts any registered applications.

/a

This switch aborts a previously scheduled shutdown command.

/p

This option immediately shuts down and powers off the computer rather than giving the user any notice or warning.

/h

The /h switch tells the computer to hibernate rather than shut down.

/e

This option records the reason for the unexpected shutdown.

/m \\computername

This option issues the command against a remote computer rather than the local computer. If you forget this option, you will be shutting down the local computer, which is an inconvenient and common mistake.

/t xxx

With this switch, time before the shutdown command is executed. The default is 30 seconds, but can be number of seconds up to 10 years in duration.

/c “Comment”

This option comments on the reason for the shutdown. You are limited to 512 characters.

/f

/f forces running applications to be closed. Unsaved data in applications will be lost.

/d [p|u]xx:yy

This option provides the reason to shut down the tracker that runs on new versions of Windows (Windows 2003, Windows 2008, and Windows 7). The shutdown is either Planned or Unplanned. Refer to the output of the help command to determine appropriate values to use in the xx and yy positions.

A typical shutdown command to reboot a remote computer named testpc would look like:

shutdown.exe /t:60 /r /m \\testpc

tasklist

The tasklist command is used to display the currently running tasks or presses. This is the same list you can see if you run the Task Manager, which is covered in Book 6, Chapter 3.

Tasklist run by itself shows you all of the processes running on the computer and displays the following information:

  • Image name: The name of the executable that is running.
  • PID: The process ID is a unique number assigned to the process.
  • Session name: The session that is running the process. There will be a services and console session in addition to sessions for each user actively on the computer.
  • Session#: Each session will have a corresponding number, with services being 0 and the console being 1.
  • Mem Usage: The amount of memory (physical and virtual) being consumed by the process.

To see verbose output, you can use the switch /V, which adds Status, User Name, CPU Time, and Window Title to the information displayed. To change the format of the output, you can use the switch /FO, which takes the parameters Table, List, or CSV, the latter used to export the data to Microsoft Excel or a spreadsheet application. Finally, you may also use the switch /FI to filter the data being displayed by any of the display columns. Use the /? Switch to view all of the options for filtering. You are able to use the /FI option multiple times to filter the list down to exactly what you are looking for.

taskkill

To go along with tasklist there is the taskkill command. In the same way that you will go to Task Manager to terminate applications or background processes, you may want to use taskkill to terminate these processes. To terminate a process with the taskkill command, you will need to specify a PID (/PID), an image name (/IM), or a filter (/FI), which specifics multiple processes to remove. The filter options for taskkill are the same as for tasklist, so you can use tasklist to ensure that you are correctly filtering the list of processes to kill. Here is a sample taskkill command to terminate all copies of notepad.exe running on a computer named Win7-AP1:

taskkill /S Win7-AP1 /U Win7-AP1\Administrator /FI imagename eq notepad.exe

technicalstuff Using the switch /S enables you to run both the tasklist and the taskkill commands against another computer on the network, rather than against your local computer.

Getting Active with Group Policy

Microsoft Active Directory (AD) stores and applies configuration settings to both users and computers that are members of the AD domain. These settings are stored in Group Policy Objects (GPO) and are automatically applied every 90 minutes as well as when the computer starts up and when a user logs on. Two commands are helpful when working with GPO settings: gpupdate and gpresult.

gpupdate

It is not always possible to wait 90 minutes to have a GPO change show up on your computer. If you were to always have to wait, then testing of changes would take days or weeks. The solution to this waiting is gpupdate, which can be used to force an immediate update of the client-side policy settings. The settings in the GPO can be targeted to the user or to the computer. Table 5-6 lists the options that are used with gpupdate.

TABLE 5-6 Switches for gpupdate

Switch

Description

/Target:{Computer|User}

By default, both user and computer policies are updated when the gpupdate command is executed. /Target allows you to specify just user or computer policies.

/Force

This option applies all policies again, rather than only the changed polices.

/Wait:{Value}

This option specifies the amount of time for policy processing to complete. The default time is 600 seconds.

/Logoff

This option logs the user off after the policy processing is completed. Some policy processing of user settings requires that the user logs off in order for the settings to take effect. Folder redirection would be one example of these settings. This setting is ignored if there are no relevant settings applied.

/Bootings

This option triggers a reboot after the policy processing is complete. Some policy processing of computer settings requires that the computer restarts in order to apply the settings. An example of this setting would be computer-targeted software installations. This switch will be ignored if no relevant settings are processed in the policy.

/Sync

sync forces the next set of policy processing to be foreground. Foreground processing occurs when a user logs on or when a computer reboots.

The following example command performs an update of user settings and processes all policy settings:

gpupdate /target:user /force

gpresult

When you want to know what policies are being applied to a computer or to a user, gpresult is your friend. The gpresult command generates a report or listing of all of the settings that have been applied through the series of GPO updates that relate to the user or computer. This report is also referred to as Resultant Set of Policy (RSoP). Table 5-7 show the most common switches used by gpresult.

TABLE 5-7 Switches for gpresult

Switch

Description

/S system

Rather than running against the location machine, /S allows you to specify a remote computer for the command.

/U domain\user

Using this option allows you to run the command as another user.

/P password

Use this option to provide the password for the specified user.

/SCOPE scope

This options specifies if the results should be generated for the “USER” or the “COMPUTER.”

/USER domain\user

This option specifies which user for which you would like to evaluate the policies.

/X filename

Use this option to generate output files in an XML format.

/H filename

Use this option to generate output files in an HTML format.

/F

This option will overwrite existing output files.

/R

To display the Resultant Set of Policies (RSoP) you will use this option.

/V

This option will provide verbose output.

/Z

If verbose is not enough, this option will provide super verbose output.

The following is an example of the gpresult command in action. This command will generate an HTML report for computer-based GPO settings and will include verbose information:

gpresult /H c:\GPResult.html /SCOPE COMPUTER /V

After it is generated, the report can be viewed in Internet Explorer.

Working with Other Useful Commands

The rest of the utilities in this chapter defy easy classification. Although they serve a wide range of functions, they are all important in your computer’s usage.

attrib.exe

All files have five basic attributes:

  • a: Archive. Files that have been modified.
  • h: Hidden. Are not usually visible.
  • i: Not to Be Indexed. Should not be included by the system indexing service. This attribute was added in Windows Vista.
  • r: Read-only. Cannot normally be deleted, nor can they be modified.
  • s: System. Have special file protection so that you may not delete or modify them.

tip The archive attribute is used by some backup utilities to identify changed files for incremental backups.

The attrib command allows you to change these attributes. The attributes are added or removed from files by specifying the attribute with a + or - character in front of the filename, as in the following statement:

attrib -s -h +a +r c:\*.sys

The preceding statement removes the system (s) and hidden (h) attributes while adding the archive (a) and read-only (r) attributes. Adding /s to the end of the line would apply the same attributes to all the files in the sub-directories as well.

diskpart.exe

To manage disk partitioning, if the need ever arises, Windows uses the Disk Management graphical disk partitioning tool. Windows also uses another command line tool: diskpart.exe. Although this tool is capable of all disk partitioning tasks, you need to use this tool only to perform rare disk partition changes that Disk Management cannot perform, such as expanding a partition on a basic disk. The need to use diskpart.exe has been reduced with the introduction of Windows 7, which incorporates the ability to expand those partitions into the Disk Management graphical tool.

The reason for not using diskpart.exe is that its user interface is awkward. To illustrate the interface, Listing 5-1 holds the steps required to create a partition on a disk and format the drive (extra blank lines have been removed):

LISTING 5-1: Creating a Partition on a Disk and Formatting the Drive

C:\>diskpart.exe
DISKPART>list disk
Disk ### Status Size Free Dyn Gpt
-------- ---------- ------- ------- --- ---
Disk 0 Online 6142 MB 0 B
Disk 1 Online 510 MB 0 B
Disk 2 Online 6142 MB 6142 MB

DISKPART> select disk 2
Disk 2 is now the selected disk.

DISKPART> create partition primary size=1000
DiskPart succeeded in creating the specified partition.

DISKPART> list partition
Partition ### Type Size Offset
------------- ---------------- ------- -------
Partition 1 Primary 1004 MB 32 KB

DISKPART> select partition 1
Partition 1 is now the selected partition.

DISKPART> assign letter=f
DiskPart successfully assigned the drive letter or mount point.

DISKPART> exit
Leaving DiskPart…

C:\>format f: /fs:ntfs
The type of the file system is RAW.
The new file system is NTFS.
WARNING, ALL DATA ON NON-REMOVABLE DISK
DRIVE F: WILL BE LOST!
Proceed with Format (Y/N)? y
Verifying 1004M
Volume label (ENTER for none)? More Data
Creating file system structures.
Format complete.
1028128 KB total disk space.
1020600 KB are available.

This process could have been completed through a single wizard in Disk Management, with less effort.

format.com

Using the format.com command prepares a disk to be used by your computer. The purposes of this command are to

  • Check whether all clusters on the partition are in working order.
  • Create the directory table.

On FAT partitions, the directory table is referred to as the File Allocation Table. The directory table maintains a list of where each file starts on the disk.

The format command requires a drive letter and supports additional switches. The proper syntax to format your A: drive is

format a:

You could modify the command by adding /q to the end of the line to perform a quick format of the drive.

tip The quick format doesn’t check the integrity of the sectors on the drive but only deletes and re-creates the directory table.

You can use /FS:filesystem to specify the format of the partition as FAT, FAT32, exFAT, UDF, or NTFS, and Windows 8.1 adds support for RdFS.

expand.exe

The command line utility expand.exe is used to expand individual source files that are shipped in a compressed format on your OS CD or from other sources. This utility can also be used to replace corrupt files being used by the OS.

On older Window OSes, files that have been compressed for expansion with expand.exe are found on your OS CD and have the last letter of their filenames replaced with an underscore. They may also be compressed as CAB files. The latest versions of Windows no longer make use of compressed files that are used with expand.exe.

Common tasks for which you might use expand.exe include

  • Viewing the names of all files in a CAB file, such as seeing the names of all GIF files contained in iis6.cab file, where D: is the drive letter of the CD drive that contains file:

    expand.exe –D D:\iis6.cab –F:*.gif

  • Extracting a file from a CAB file, such as extracting the IIS_winxp.gif file from the iis6.cab file to the root of the C: drive:

    expand.exe D:\iis6.cab –F:IIS_winxp.gif C:\

  • Expanding a compressed file, such as extracting a fresh copy of the Freecell Help file to the root of the C: drive:

    expand.exe D:\freecell.ch_ c:\freecell.chm

help

If you need to know how to do something with the command line, you have two main options. All commands support /? as a switch to get additional information on how to use the command. Additionally, Windows also has a help command.

Use help followed by the command that you would like to get help on: for example

help help

If you use help by itself, you get a list of commands that you can request help for.

Getting an A+

The most important things to remember from this chapter are what the different commands are used for and the major differences between similar commands. Here is a quick review:

Prep Test

1. You are working on the help desk, and you receive a call from Mary. She is looking for a file that is saved on her hard drive. She has forgotten the name she gave it, but she knows that the title contains the word “budget” and that it is a Microsoft Excel spreadsheet. What command will best help her locate her document?

(A) dir *budget.xls

(B) dir *budget*.xls /b

(C) dir *.budget*.xls /s

(D) dir *budget*.xls /b /s

2. You need to regularly back up files in a directory, but you want to back up only files that have changed. What commands can you use to accomplish this in the easiest way possible?

(A) fc and xcopy

(B) attrib and copy

(C) fc, changes, and xcopy

(D) xcopy and attrib

3. You want to copy a directory structure (complete with sub-directories), so you use copy c:\dir1\*.* c:\newdir /s /e. What will you find in the newdir directory?

(A) All files that were in dir1

(B) All files and sub-directories that were in dir1

(C) Nothing — the command is improperly constructed and will generate an error

(D) None of the above

4. You receive a call from a user on your network complaining that his computer is slow. You ask a few more questions and find out that he feels that the speed of his hard drive is much slower than when he got his computer. What command would you suggest running?

(A) diskfix

(B) bootrec

(C) scanfix

(D) defrag

Answers

  1. D. Although C looks like a good choice as well, using the sub-directory switch, it has an additional period in the search string, so will not return as many files and will work only if Mary’s document has a period in front of the word budget. See “dir.”
  2. D. The attrib.exe command can be used to remove the archive attribute from all files in a directory structure. Then, as files are modified, you can use xcopy *.* c:\backuplocation /s /a to copy all the files to a new location. If you want your next copy to copy the files that were modified since the last copy, you have to use the attrib command to remove the archive attribute again. Check out “xcopy.”
  3. C. The suggested command will cause a syntax error, and nothing will be copied. The copy command does not support either /s or /e; to use these options, you have to use the xcopy.exe command. Peruse “xcopy.”
  4. D. defrag is used to reorganize files, which speeds up access to the disk. Check out “defrag.exe.”