It might seem odd that in a book about the latest and greatest Windows operating system, we would devote an entire chapter encouraging you to use the text-based command-line world, turn your back on 40 years of software advancement, and choose to work in an environment that is proudly stuck in the 1970s. Well, we’ll let you in on a little secret: The keyboard is mightier than the mouse—and a lot faster.
Why is that so? As many power users and experienced administrators already know, it’s usually much faster to type a few letters to do a job than to take your hands off the keyboard and poke around at endless menus and screens with a mouse or your fingertip. In almost every Windows configuration, you can perform setting and diagnostic tasks from the command line with just a few quick keystrokes (after you’ve memorized the fairly cryptic things that you have to type, of course). Many important diagnostic tools, such as ping
, tracert
, and nslookup
, are available only from the command line, unless you purchase third-party graphical add-ons to perform these functions.
Tip
Here’s some great news: Microsoft has finally, after 15 years without any changes to the command-line environment, made significant improvements in the Windows 10 version. We tell you about these improvements later in the chapter under “Copying and Pasting in the Command Prompt Window.”
Although the term batch file might bring back uncomfortable memories of the old MS-DOS days, batch files and program scripts are still powerful tools that provide a useful way to encapsulate common management functions. Together, command-line utilities, batch files, and scripts based on Windows Script Host and Windows PowerShell provide a complete set of building blocks from which you can develop high-level tools for repetitive or complex tasks.
In this book, we give you a quick introduction to setting up and using the command-line environment. We don’t have room for more than that. For much more detail, tutorials, examples, and many helpful tips on using command-line tools, check out Brian’s book Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools, published by Que. (The book’s title is now dated, but the content remains relevant.)
The Command Prompt window lets you type commands and review output, as shown in Figure 30.1. The quickest way to open a Command Prompt window is to use the keyboard: Press Windows Logo+X and then press the shortcut key C or select Command Prompt.
If Command Prompt is not one of the menu choices but Windows PowerShell is, see “Command-Line Access from the Power User Menu,” p. 693.
Alternatively, you could perform one of the following actions:
Right-click or touch and hold the Start button, then select Command Prompt.
Press Windows Logo+R; then type cmd and press Enter.
In the taskbar’s search box, type cmd and wait a moment. On most computers, “Command Prompt” will appear as the only search result. Press Enter to launch it.
Open File Explorer and select any folder or drive. Then select File, Open Command Prompt, Open Command Prompt.
On the bottom left of the Start menu, select All Apps and then locate Command Prompt in the Windows System section.
Tip
If you plan on using the Command Prompt window regularly, open a Command Prompt window by one of the means mentioned previously. Locate its icon in the taskbar—it has the tiny characters C: in white, against a black background. Right-click it and select Pin This Program to Taskbar. Now you can easily open a Command Prompt window anytime you want, with just a click.
All these methods work equally well.
The main difference between a standard Windows application and a command-line program—which in Windows is technically called a console program—is that it doesn’t use a graphical display or pull-down menus. Instead, you type commands into the Command Prompt window to tell Windows to do something, and the programs type information back to you. Each command line starts with the name of the program that you want to run, optionally followed by additional information called arguments. Arguments tell the program what specifically you want to do. Each program has its own rules about what its arguments signify, which arguments might be required, and which are optional.
When you are working in the command-line environment, the active location (drive and folder) is known as the current directory. The current directory is significant because if you don’t specify a location argument with a command that requires one, the current directory is assumed. You can change the current directory by using the cd
command like this:
cd windows
If you want to change the current drive letter as well as the current directory, put /d
on the cd
command line, as in cd /d d:setup.
The output of a command-line program usually prints out in the Command Prompt window. You can save output by redirecting it into a file using the >
character. For example, the command
dir >listing.txt
lists the files in the current directory and stores the results in the file listing.txt
. You could then type the command notepad listing.txt to view the results. By itself, >
creates a new file or replaces an existing file. You can tack output onto the end of (append to) a file using >>
, as in this example:
dir c:windows >>listing.txt
You can also send the output of one program to another program using |
(the pipe character), as in
dir c:windows | findstr /i setup
which lists the contents of folder c:windows
and prints out only entries that contain the word setup somewhere in the name. One handy use of the pipe mechanism is to send output to the command more
, which stops after it displays each screenful, so you can read through a long printout:
dir c:windows | more
When it stops printing, you press the spacebar to see the next screen.
There are more ways to redirect program input and output. For more information, visit technet.microsoft.com and search for “Using Command Redirection.”
When you type a command, Windows searches first in the current directory, and then in a list of folders called the search path, for a file whose name matches the program name you typed and whose name ends with any of several extensions, such as .exe
, .bat
, or .vbs
. The most common program extensions are listed in Table 30.1. Windows examines the file to see what type of program it is and then runs it. It’s then the program’s job to interpret any arguments you typed after the program name.
The search path is defined by a list of folder names in the PATH
environment variable, and the complete list of extensions that Windows looks for is defined in the PATHEXT
environment variable. The default search path includes the following folders:
C:Windowssystem32
C:Windows
C:WindowsSystem32Wbem
C:WindowsSystem32WindowsPowerShellv1.0
This means that you can run any program file, batch file, or script stored in the current directory or in any of these folders simply by typing its name. You can start both Windows programs and command-line programs in this way. For example, you just have to type notepad and press Enter to start the Notepad accessory.
If you create your own batch files, scripts, or programs, it’s a good idea to create a separate folder in which to store them, and to put that folder in the search path. We show you how to do so later in this chapter, under “Setting the PATH
Environment Variable.”
When you press Windows Logo+X, or right-click or touch and hold the Start button, Windows displays the Power User pop-up menu. This incredibly useful shortcut gives you instant access to nearly every Windows management tool.
The Power User menu has entries that launch a command-line window, but you must choose which command-line environment appears on the menu: either the traditional Command Prompt window or Windows PowerShell, which we discuss later in the chapter.
You can choose which environment appears on the menu by following these steps:
1. Press Windows Logo+X, or right-click or touch and hold the Start button.
2. Select Control Panel, Appearance and Personalization, Taskbar and Navigation, then select the Navigation tab.
3. To have the menu launch the traditional Command Prompt, uncheck Replace Command Prompt with Windows PowerShell. To have it launch Windows PowerShell, check Replace Command Prompt with Windows PowerShell. Then click OK.
The Power User menu actually displays two entries for your chosen command-line environment. The second entry has (Admin) added to the name. That selection launches an elevated version of the program that has full administrative access, as discussed in the next section.
For what it’s worth, if all you are doing at the Command Prompt is starting up programs by typing their names, either environment works equally well. As discussed later in the chapter, Windows PowerShell provides advanced processing tools within command lines, but basic commands like dir
operate very differently in the two environments.
Some command-line programs require elevated Computer Administrator privileges (via User Account Control) to do their job correctly. To use a Command Prompt window to run a program with elevated privileges, you must run it from a Command Prompt window that is itself elevated.
To learn more about User Account Control (UAC) and elevation, see “User Account Control,” p. 101.
When UAC is enabled (and we believe it always should be), you must take deliberate action to open an elevated Command Prompt window. Use one of these methods:
Press Windows Logo+X, or right-click the Start button or touch and hold the Start button. Then select Command Prompt (Admin).
If Command Prompt (Admin) is not one of the menu choices but Windows PowerShell (Admin) is, see “Command-Line Access from the Power User Menu,” p. 693.
If you have pinned Command Prompt to the taskbar, right-click the taskbar icon, right-click Command Prompt in the pop-up menu, and then select Run As Administrator.
Open File Explorer and select any folder or drive. Then select File, Open Command Prompt, Open Command Prompt As Administrator.
In the taskbar’s search box, type cmd. Right-click the Command Prompt result, or on a touch screen, touch and hold until the pop-up menu appears. Select Run As Administrator.
Caution
Be very careful when using an elevated Command Prompt window. Any commands you start from within this window will run with elevated privileges from the get-go, and you will receive no further UAC prompts when you start them. This includes Windows GUI programs. For example, if you type the command optionalfeatures, you will get the Turn Windows Features On or Off dialog box, and you will not have to confirm anything before it starts.
If you want, you can set a Command Prompt shortcut or pinned taskbar icon so that it is elevated by default. Right-click the icon. If you’re working with a pinned taskbar icon, right-click Command Prompt. Then, select Properties. On the Shortcut tab, click the Advanced button and check Run As Administrator. Be sure to rename the shortcut so that it’s clear that it opens an elevated prompt.
To be safe, do not use an elevated Command Prompt window for general-purpose work. Use it only to accomplish a specific task that requires elevated privileges; then close it.
Although you will usually use output redirection to store the output from command-line programs in files, you can also use cut and paste to move text into or out of a Command Prompt window.
Here’s an area where Windows 10 offers real improvements over previous versions of Windows. If you enable the new keyboard shortcut options and QuickEdit mode, you can copy and paste text in console applications just as you would in Windows apps. The mouse cursor selects text in a natural way, and the standard Ctrl+C and Ctrl+V keyboard shortcuts copy and paste, respectively.
To enable the new options, open a Command Prompt window as described previously. Right-click the window’s title bar and select Properties. Select the Options tab (shown in Figure 30.2) and make the following settings:
Under Edit Options, check all four boxes. Quick Edit lets you select text simply by clicking and dragging the mouse cursor. Insert Mode inserts rather than overtypes characters by default when you backspace and type more into a command line. Enable New Ctrl Key Shortcuts lets you use Ctrl+C and Ctrl+V to copy and paste and Ctrl+F to search for previous commands. Filter Clipboard Contents on Paste removes tabs from pasted text and turns “fancy” quotes and dash characters into their simple "
and -
equivalents.
Under Text Selection, check both boxes. Enable Line Wrapping Selection makes the cursor select text the way it does in a word processor, wrapping from line to line rather than selecting a rectangular region. (If you need to use the old rectangular mode, just hold down the Alt key while selecting text.) Extended Edit Keys enables a bunch of keyboard shortcuts that you can use to adjust the range of selected text before you copy it to the Clipboard.
While you’re at it, select the Layout tab and check Wrap Text Output on Resize. With this option checked, if text output in the console window wraps onto multiple lines, you can enlarge the window to untangle it.
The Extended Edit Keys option enables shortcuts such as Ctrl+A to select all text in the window, Ctrl+M to start “marking” (selecting) text at the cursor position, and Shift+End to extend the selection to the end of the current line. But there are way more new keyboard tricks than we can describe in our limited space here. If you’re interested, click the Find Out More About New Console Features link on the Options tab of the Properties page.
Note
If you use old console applications or MS-DOS applications and they stop working correctly when you enable these new keyboard and mouse options, try disabling QuickEdit mode. If that doesn’t help, check Use Legacy Console on the Options tab of the Properties page. This makes Windows revert to the same console window code that it used in Windows XP through 8.1.
By the way, even with the new options enabled, the old methods of copying and pasting still work. To paste text into the window at the cursor location the old way, you can right-click the window’s title bar and then select Edit, Paste. Or you can use the keyboard: Press Alt+Spacebar and type E P.
To copy text from the window to the Clipboard the old way, right-click the window’s title bar and select Edit, Mark. Alternatively, press Alt+Spacebar and type E M. Use the mouse to highlight an area of the screen, and then press Enter. This copies the text to the Clipboard.
Starting with Windows 10, the Command Prompt window can be made partially transparent so that you can see the contents of windows behind it. It’s not everyone’s cup of tea, but many system administrators have become used to this capability on the Linux and Unix operating systems and like it. To make a console window transparent, right-click its title bar and select Properties. Select the Colors tab and adjust the Opacity slider.
How do you know what programs are available and how to use them? For that, you must turn to documentation about the command-line environment. For some reason, Microsoft no longer provides this information in the Help and Support system, but you can search online. Some programs can even be told to display their own usage information.
To get an idea of what’s available, see Appendix B, “Command-Line Utilities,” at the end of this book. And check out Brian’s book Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools.
For a general online listing, perform the following Google search:
site:microsoft.com command line a-z windows server
At the time this was written, the first search result, titled “Command-Line Reference - TechNet - Microsoft,” takes you to the command-line listing that covers several desktop and server versions of Windows. Most of the commands don’t change from one version to the next.
Many commands display information about their arguments and syntax if you run them with the /?
switch, like so:
dir /?
Windows will start any program whose name it can find in the search path, whether it’s a console application or a GUI program. If you know Windows programs by name, this capability can save you an awful lot of poking around and clicking with the mouse. Just type! Table 30.2 lists just a few GUI programs you can start by typing their name into a Command Prompt window or the Run dialog box (Windows Logo+R).
For those programs whose name ends with the .msc
filename extension, you can omit the .msc
when you type the name into a Command Prompt window. You must add .msc only when typing into the Run dialog box.
(By the way, in our books covering previous versions of Windows, I used to list many other program shortcuts, such as eventvwr.msc
to open Event Viewer. However, in Windows 10, the Windows Logo+X shortcut menu provides a much quicker path to most of the useful management tools.)
Environment variables are short, named text strings that Windows provides to each Windows and console program. Using environment variables is one of the ways in which Windows communicates information such as the location of system files and folders—as set up on your particular computer—to programs. Environment variables indicate where temporary files are stored, what folders contain Windows program files, and other settings that affect program operation and system performance. In addition, they can be used in batch files to temporarily hold information about the job at hand.
In Windows 10, the initial environment variables for a Command Prompt window are configured using the GUI shown in Figure 30.3.
This dialog box has two sections: System Variables and User Variables. The lower section, System Variables, defines the environment variables set up for every user account. The upper section, User Variables, defines additional default environment variables just for the current user account. They add to or override the variables set up in the systemwide list.
To open this dialog box, if you are signed in with a Computer Administrator account, use either of these methods:
If you have a Command Prompt window open, type the command sysdm.cpl and press Enter. You might need to confirm a UAC prompt. Then select the Advanced tab and click the Environment Variables button.
Alternatively, open the Start menu, select Settings, type envir in the Search box, and select either Edit Environment Variables for Your Account or Edit the System Environment Variables.
You can now edit both the upper User Variables (personal settings) and lower System Variables (systemwide settings) lists.
If you are not signed in with an Computer Administrator account, the process is a bit trickier. Use either of these procedures:
To edit the systemwide settings, you can use either of the preceding methods, but you’ll have to select a Computer Administrator account and supply its password. Don’t change the upper (personal) part of the dialog box; you will be changing settings for the wrong account.
To edit your own personal environment variable list, open the Control Panel (one way is to press Windows Logo+X and select Control Panel). Then select User Accounts and Family Safety, User Accounts. In the task list at the left side, click Change My Environment Variables. You will be able to edit only the upper (personal) environment variable list.
After you have the dialog box open, you can create new variables, delete variables, or highlight and edit existing variables using the corresponding buttons.
If you need to alter a variable, you must understand what happens if a conflict exists between environment variables defined in both the System Variables and User Variables lists. As a rule, Windows examines several locations for definitions, and the last definition seen wins. Windows sets variables from the following sources, in this order:
1. The systemwide variable list.
2. The personal variable list. (At this step, the PATH
variable is treated specially. See the next section for details.)
3. Commands set in autoexec.nt
. (This applies only for MS-DOS or Windows 3.x applications. See “The MS-DOS Environment” later in the chapter for more information.)
4. Subsequent definitions issued by set commands typed in a Command Prompt window or encountered in a batch file. These changes apply only to that particular window and will disappear when the window is closed.
If you write batch files or scripts, it’s useful to put them into one folder and to add this folder name to the PATH
variable so that you can run your batch files and scripts simply by typing their names.
Because misediting the PATH
variable can prevent Windows from finding applications it needs to run, Windows gives the PATH
definition special treatment:
For the PATH
variable, the User Variables definition is appended to the System Variables definition.
For all other environment variables, a User Variables definition overrides a System Variables definition.
In other words, you can enter your own personal folder(s) into the User Variables definition of PATH
for your user account, without worrying about copying or messing up the system definitions.
To create a folder for your own scripts and batch files, use one of these two procedures:
If you want to use the scripts and batch files only for your own use, create a folder and put the full path to the folder into your personal PATH
variable. For example, create a folder named c:scripts
.
Then add a PATH
variable to the upper part of the Environment Variables dialog box (refer to Figure 30.3) with the value c:scripts
. If you need to add more than one folder to your personal PATH
, put a semicolon (;) between each folder name.
If you want to create scripts and batch files that can be used by anyone who uses your computer, create a folder and be sure that its permissions are set so that all users can read it.
For example, create a folder named c:scripts
. Right-click the folder, select Properties, and select the Security tab. If Users does not appear under Group or User Names, click Edit, click Add, and then add Users to the list. Be sure that the Read & Execute permission setting is checked.
To learn more about editing permissions, see “Setting Security Permissions on Files and Folders,” p. 754.
Carefully edit the PATH
variable in the lower part of the Environment Variables dialog box (shown in Figure 30.3). Add a semicolon (;) to the end of the existing text and then add the folder name c:scripts
.
Your folder now will be part of the PATH
when you open a new Command Prompt window.
If you still use MS-DOS programs, you’ll be glad to know that the 32-bit x86 processor versions of Windows 10 still support these programs.
The 32-bit versions of Windows run MS-DOS applications inside a program called ntvdm
, which stands for Windows NT Virtual DOS Machine. Ntvdm
is also used by the Windows 3.x support environment. It simulates the environment that DOS programs expect and makes them work correctly under Windows. Ntvdm
runs automatically when you attempt to start an MS-DOS or 16-bit Windows program.
If you’re experiencing difficulties while running a specific DOS program, find the program file or a shortcut to it. Right-click it and choose Properties.
Note
The MS-DOS and 16-bit Windows subsystems are not provided with ARM processor or 64-bit versions of Windows. (It’s a technical limitation, not a marketing decision.) If you use a 64-bit version of Windows and still need to run MS-DOS or Windows 3.1 applications, you can set up a virtual machine; install a copy of MS-DOS, Windows 3.1, or a 32-bit version of Windows on it; and run your older applications inside the simulated environment. We address this issue in Appendix A, “Virtualization.”
Poke through each tab and use the ? (question mark) button for help on the settings. Educational and game programs often require you to adjust the Memory and Compatibility settings.
You can choose to further configure the MS-DOS and Windows 3.x environment by modifying Windows 10’s equivalent of the old CONFIG.SYS
and AUTOEXEC.BAT
files. These files, called config.nt
and autoexec.nt
, are used to configure ntvdm
each time it’s started up. You can edit the config.nt
and autoexec.nt
files with a simple text editor such as Notepad. They’re protected files, however, so you must run an elevated version of Notepad using this procedure:
1. In the taskbar’s search box, type the word notepad.
2. When Notepad appears as a search result under Apps, right-click it and select Run As Administrator.
3. Confirm the UAC prompt, or enter a Computer Administrator password as requested. (Alternatively, you can just type notepad in an elevated Command Prompt window.)
4. Click File, Open and browse to windowssystem32
. Select autoexec.nt
or config.nt
as desired.
Most of the settings used in MS-DOS 6 still work in config.nt
, with some exceptions. For more information about configuring the MS-DOS environment in Windows, go to google.com and enter this search: site:technet.microsoft.com windows xp devicehigh. Select the result titled Devicehigh. The left pane will display a list of MS-DOS configuration commands.
Note
On 32-bit x86 versions of Windows 10, the first time you try to run a DOS or Windows 3.1 program, Windows will prompt you to install ntvdm
, which is a system component that lets you run these 16-bit apps inside Windows. There is also a Control Panel applet that lets you turn the 16-bit support subsystem on or off. Search Control Panel for 16-bit Application Support. The Registry value that controls the subsystem is DisallowedPolicyDefault
, in key HKEY_LOCAL_MACHINESystemCurrentControlSetControlWOW
. On a corporate network, the network administrator may permanently enable or disable the subsystem through Group Policy.
The MS-DOS enhancement ANSI.SYS
was used to let programs move the cursor around on the screen. You can make it available for MS-DOS programs simply by adding the line device=ansi.sys
to config.nt
.
Tip
When adding ANSI.SYS
to config.nt
, it’s a good idea to change the line files=40
to files=100
. Most of the MS-DOS applications that are still useful today require more than the paltry default allowance of open files, and the memory use to support more is no longer a worry.
DOSKEY
—which has been enhanced significantly from the old DOS days—functions only in the 32-bit Windows console environment, and even if you attempt to load it in autoexec.nt
, it does not function within the MS-DOS COMMAND.COM shell.
Most DOS applications can print only to LPT ports. If you want to use a printer that is on a USB port or is out there somewhere on a LAN, you must share the printer (even if it’s just attached to your own computer and you’re not using a network) and then issue the command
net use lpt2: \localhostsharename
from the Command Prompt window, replacing sharename with the name you used when you shared the printer. Direct your DOS program to use LPT2. (You can use LPT1, LPT2, or LPT3, but you must select an LPT port number that does not have an associated physical LPT port in your computer.) Some MS-DOS applications know how to send output directly to networked printers using a UNC share name, so you don’t need to use the LPT trick with them.
If you make changes to autoexec.nt
or config.nt
after having run an MS-DOS program from a Command Prompt window, you must close the Command Prompt window and open a new one for the MS-DOS subsystem to reload and take on the new configuration.
For more information about the net use command, see “Managing Network Resources Using the Command Line,” p. 483.
Although Windows Script Host and Windows PowerShell are more powerful tools for creating your own scripts, it’s also useful to know how to use the batch file language. Batch files let you take advantage of the many command-line programs supplied with Windows.
A batch file, at the simplest level, is just a list of Command Prompt commands that have been typed into a file whose extension is .bat
or .cmd
. When you enter the name of a batch file at the Command Prompt, Windows looks for a file with this name in the current directory and in the folders of the PATH
environment variable. Windows treats each line in the batch file as a command, and runs them one after the other as if you had typed the commands by hand. At this simplest level, a batch file can be a big help if you find yourself typing the same commands over and over.
Beyond this, there are several commands that you can use to write rudimentary programs within a batch file so that it can take different actions depending on what you type on the command line, or depending on the results of the commands it executes. These programming commands have been greatly improved since the MS-DOS days, so writing useful batch files on Windows 10 is much easier now. In particular, the IF
and FOR
statements have been greatly extended. You can prompt the user for input. It’s possible to manipulate strings and filenames and perform arithmetic calculations. You can create subroutines within a single batch file. And there’s more.
Unfortunately, we don’t have room to provide coverage of batch file programming in this book, but check out Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools, written by yours truly and published by Que.
Some Microsoft documentation is also available online. After reading this chapter, go to www.microsoft.com and search for these phrases:
Command Shell Overview
Environment Variables
Using Batch Parameters
Using Batch Files
Using Command Redirection Operators
Cmd
Command-Line Reference
Then open a Command Prompt window and type the commands
help cmd
help set
help for
help if
and so on.
Table 30.3 lists several short batch files that I put on every computer that I use. These short command scripts let me edit files, change the path, view a folder with File Explorer, and so on, simply by typing a couple of letters followed by a folder or filename. They don’t involve fancy programming, but they save me a significant amount of time when I’m working with the Command Prompt window.
Tip
To learn how to get the most from the batch files and the command line, get Brian’s book Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools. The content applies to Windows 10.
If you create a c:scripts
folder and add it to the PATH
, as discussed earlier under “Setting the PATH
Environment Variable,” you might want to create these same batch files in that folder for your own use.
Batch files, which are discussed in the previous section, are great at performing a simple sequence of steps. But it’s not always easy to write a batch file for a task that involves decision making, where you have to perform different actions under different circumstances, or when you need to do math or manipulate text and other data. For more complex tasks, there is a more powerful tool called Windows Script Host (WSH).
Scripts written for WSH can massage, digest, and manipulate text files and data, view and change Windows settings, and more. Scripts have an advantage over batch files in that they can perform complex calculations and can manipulate text information in powerful ways because you write them in a full-featured programming language. In addition, scripts can send email, manipulate files and folders, and even enlist applications such as Microsoft Word and Excel to present information in tidy, formatted documents and charts.
The “Host” part of the tool’s name comes from the fact that it provides a structure for running scripts written in several different programming languages. Windows comes with built-in support for two different scripting languages:
VBScript—Nearly identical to the Visual Basic for Applications (VBA) macro language used in Word and Excel.
JScript—Microsoft’s version of the JavaScript language, which is widely used to make web pages interactive. (JavaScript, by the way, is not the same thing as Java. Java is another programming language altogether.)
In addition, you can download and install scripting support for other languages. If you have a Unix or Linux background, for example, you might want to use the Perl, Python, or TCL scripting languages. You can get free WSH-compatible versions of these languages at www.activestate.com.
If you are already versed in one of the scripting languages mentioned here, by all means, use it. If you don’t already know a scripting language, VBScript is probably the best one to start with because you can also use it to write macros for Microsoft’s desktop applications. We use VBScript in the examples in this section.
We don’t have room here to give you even an introductory course in VBScript programming. As mentioned, that topic can fill an entire book. What we can do is give you some examples of how WSH can be used to perform useful tasks and to manage Windows. These sample scripts assume that you have set the default script environment to console mode, as opposed to windowed mode, by typing this command just once in an elevated Command Prompt window:
cscript //h:cscript //nologo //s
For instructions on opening an elevated Command Prompt window, see “Running Commands with Elevated Privileges,” p. 693.
WSH comes with tools to examine and modify drives, folders, and files. Here is an example of a VBScript script that performs a reasonably useful task: It displays the amount of free space on each of your computer’s drives.
set fso = CreateObject("Scripting.FileSystemObject")
set drivelist = fso.Drives
for each drv in drivelist
if drv.IsReady then
wscript.echo "Drive", drv.DriveLetter, "has", drv.FreeSpace, "bytes free"
end if
next
Type this script into a file named freespace.vbs
in your batch file directory, and then type the command-line command freespace. On my computer, this prints the following:
Drive C: has 15866540032 bytes free
Drive D: has 27937067008 bytes free
Drive F: has 335872000 bytes free
Drive H: has 460791808 bytes free
WSH can also work with networking features. The following VBScript script displays your computer’s current network drive mappings:
set wshNetwork = CreateObject("WScript.Network") ' create the helper object
set maps = wshNetwork.EnumNetworkDrives ' collection describes mapped drives
for i = 0 to maps.Length-2 step 2 ' step through collection by twos
wscript.echo "Drive", maps.item(i), "is mapped to", maps.item(i+1)
next
Windows Management Instrumentation (WMI) is a system service that provides access to virtually every aspect of a Windows computer system, from the hardware components up to the highest-level system services.
The following script lists the status of each system service installed on your computer. This script file can be named showservices.vbs
. (The underscores at the end of some of the lines are part of the script.)
set services = GetObject("winmgmts:{impersonationlevel=impersonate," & _
"authenticationlevel=pkt}!" & _
"/root/CIMV2:Win32_Service") ' get services WMI info
for each svc in services.Instances_ ' display information for each service
wscript.echo svc.name, "State:", svc.State, "Startup:", svc.StartMode
next
On my computer, the first few lines of output from this script look like this:
AJRouter State: Stopped Startup: Manual
ALG State: Stopped Startup: Manual
AppIDSvc State: Stopped Startup: Manual
Remember, too, that because these are command-line programs, you can redirect the output of these scripts into a file. The following command puts the service list into the file listing.txt
, which you could then view and edit with Notepad:
showservices >listing.txt
Not satisfied with the programming power provided by Windows Script Host, Microsoft went on to create yet another scripting and management tool called Windows PowerShell (WPS), which debuted in Windows 7. In many ways, WPS looks and acts like the familiar Command Prompt window, but it’s actually a very strange animal, and it gives you access to some powerful programming tools. We don’t have room in this book to teach you much about it, but we do describe how it differs from batch files and scripts, and we point you to resources that will help you learn more.
We used the word strange. Can a computer program be strange? Definitely! For one thing, it’s object-oriented. Most Windows PowerShell commands (which are properly called cmdlets) generate streams of objects, not text. Objects are computer representations of real-world things. They have properties that describe attributes of the things they represent and methods that let you manipulate the things. For example, an object that represents a specific file on your hard disk might have properties such as Name, Size, and LastWriteTime, as well as methods such as Delete, Edit, and Open. Windows PowerShell works with objects in an unusual, and ultimately very powerful way.
If you type dir in a regular Command Prompt window, the command shell generates a bunch of text listing the current folder’s files by name. The dir
command is programmed very specifically to print information about files in text form. That’s all it can do.
In WPS, typing dir also prints out a list of filenames, but something completely different happens behind the scenes. In WPS, dir
is a shortcut for the Get-Childitem
cmdlet, which in its simplest use generates a stream of File objects; each object represents one of the files in a folder, and each object has properties and methods (for example, name and size). When an object (of any sort) lands in the WPS prompt window, WPS prints out a line of text listing the object’s most important properties. For a File object, this includes the file’s name, size, and the date it was created. So, when you type dir, WPS produces a stream of File objects and they end up as a nice, tabular listing of files, as shown in Figure 30.4.
The result is the same as in the old Command Prompt environment but it’s happening in a general, more abstract way. The cmdlet doesn’t know about or care about text or formatting; it simply spits out a bunch of File objects. And the WPS window will turn any list of objects into a nice tabular listing. Files, user accounts, hard drives, Windows services—whatever.
In addition, WPS includes a full-scale object-oriented programming language and has access to Microsoft’s .NET programming platform, which means WPS scripts can perform complex computations and communicate with other computers and networked (cloud) services.
To open WPS and try it yourself, you can use any of the following methods:
In the taskbar’s search box, type powershell and then select Windows Powershell from the search results.
Press Windows Logo+R, type powershell, and press Enter.
In a Command Prompt window, type powershell and press Enter. When starting this way, you can type exit to return to the normal Command Prompt environment.
The PowerShell window appears as shown in Figure 30.4.
You can also choose to have Windows PowerShell appear on the handy Windows Logo+X pop-up menu.
To put Windows PowerShell in the pop-up menu instead of Command Prompt, see “Command-Line Access from the Power User Menu,” p. 693.
WPS lets you do complex things with objects right in a command line, without writing scripts or programming. You can use the familiar | (pipe) symbol to direct streams of objects from one cmdlet to another, and this lets you do very complex, specific things with tools that are separately very simple and general-purpose in nature. For example, the following command will list all files in the current folder that are more than six months old:
dir | where-object { $_.LastWriteTime -lt (get-date).addmonths(-6)}
This command looks complex at first, but it’s not so bad. This command line strings two cmdlets together:
dir
—Spits out a list of all the File objects in the current directory. Here, they don’t land in the WPS command window, so they don’t make a text listing. Instead, the pipe (|) symbol instructs WPS to pass the objects to the next command.
Caution
The filtered file objects spill out into the WPS window, where they are printed out as a nicely formatted list. If you were, say, cleaning out a temporary or log file folder, you could extend this command to delete all the old files it found:
dir | where-object
{ $_.LastWriteTime -lt
(get-date).addmonths(-6)}
| remove-item
In this version of the command, where-object
passes file objects to remove-item
, which deletes the files. Please don’t just type this command to try it out, however, as you might inadvertently delete important Windows files in your profile folder!
where-object
—Passes just some of the objects through, based on the filtering condition inside the curly brackets. In this example, it passes through only those files that have not been changed for more than six months (that is, whose LastWriteTime
value is less than the date/time six months back). So only the objects representing old files are passed on.
As we said earlier, you’re not limited to using commands that you type into the WPS window. WPS has a full-scale programming language with variables, loops, subroutines, user-defined objects, and so on. You can use these at the Command Prompt or in script files. You also can create shortcuts (called aliases) for commonly used commands and scripts to make typing easier, and a bunch of aliases are predefined for you.
For more information about WPS, check out Brian’s book Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools or the Sams book Windows PowerShell Unleashed, 2nd Edition.
Windows Task Scheduler is an automation tool that lets you specify programs to be run automatically at specified dates and times and on certain events, such as system startup, users logging on, and even the occurrence of any event that can be logged in the Event Viewer.
When Task Scheduler runs a task as a different user than the one currently logged on, the logged-on user cannot see or interact with the program. Be sure that scheduled tasks can operate without user input and exit cleanly when they’ve done their work. And keep in mind that once an application or service is running, even if it was launched through a scheduled task, it will affect system performance just as if you started it manually.
What kinds of tasks would you run with Task Scheduler? As mentioned, the tasks need to run without user interaction. So they are typically maintenance tasks, such as defragmenting the hard disk, cleaning out temporary files, and so on. Windows uses Task Scheduler for this very purpose, and you’ll notice that several preinstalled scheduled tasks are set up when Windows is installed to do this very sort of thing.
Task Scheduler is especially useful with batch files and scripts because these scheduled programs can usually be designed to run without any user interaction. It’s truly the ultimate automation tool because you don’t even have to be there when it’s working!
Note
Obviously, the computer must be alive to run a task, so if you expect it to do a disk cleanup at 4:00 a.m., be sure to leave the computer on. If a scheduled task is missed because the computer was turned off, Windows will perform the task the next time the computer is started but the task will now be running while you’re using the computer, which is probably what you were trying to avoid by scheduling it to run at night.
There are several ways to open the Task Scheduler:
Click in the taskbar’s search box and type tasks. Then select Schedule Tasks from the search results.
Press Windows Logo+R, type taskschd.msc, and then press Enter.
At the Command Prompt, type taskschd and press Enter.
Then, in the left pane, select Task Scheduler Library.
You can create two types of tasks in Task Scheduler:
Basic tasks—Designed to be run using the current user’s account and to support a single triggering event or time.
Tasks—Can be run using any specified user account and can be configured to run whether or not the user is logged in. Tasks can also be run in Windows XP or Windows Server 2003 compatibility mode and can be configured to run with elevated priority if necessary.
To create a Basic task in Task Scheduler, follow these steps:
1. Open Task Scheduler as discussed earlier in this section. In the top-center pane, Task Scheduler displays a summary list of tasks that started and/or completed during the last 24 hours and also displays a list of active tasks below that. (Here, active means “defined and enabled to run at the specified time or event.” It doesn’t necessarily mean “actively running right now.”)
2. The Actions pane is located on the right side. Click Create Basic Task. The Create Basic Task Wizard opens.
3. Enter the name of the task and a description. Enter whatever you want, to remind you of what the task does. Click Next to continue.
4. On the Task Trigger screen, select when to run the task. You can choose daily, weekly, monthly, one time, when the computer starts, when you log on, or when a specific event is logged.
You can use the When a Specific Event Is Logged option to trigger the task when a specific Event Log entry is recorded. For example, you could use this to perform some sort of notification if a disk error event occurs. You’ll need to enter the event’s numeric ID number. (To find an event’s ID number, find an occurrence of the event in the Windows Event Log.)
5. Click Next.
6. If you chose Daily, Weekly, Monthly, or One Time, you are asked when to perform the task. Specify applicable time options, such as time of day, as required. Click Next.
7. Select what action you want the task to do (start a program, send an email, or display a message). Click Next to continue.
8. If you selected Start a Program, use Browse to locate the program, batch file, or script. (For Windows applications, browse in the Windows
or Windowssystem32
folders. For third-party applications, search in the Program Files
folders. For scripts you’ve written yourself, browse to the folder in which you’ve stored the script or batch file.) Then provide any necessary command-line switches or settings, as shown in Figure 30.5, and if you want to specify a default drive and folder for the program, enter the path to the desired folder.
If you selected Send an Email, enter the information for sender, receiver, SMTP email server, message, and so forth.
If you selected Display a Message, enter the message title and message text. Then click Next.
Tip
If you’re scheduling a Windows Script Host script, remember that you will most likely not be present when it runs, so you won’t be there to clear any message boxes that it displays. Be sure either to set cscript
as the default script processor, rather than wscript
, so that wscript.echo
statements don’t display message boxes, or be careful not to use wscript.echo
, MessageBox()
, or InputBox()
. To change the default script processor, type the command cscript //h:cscript in an elevated Command Prompt window. Alternatively, use cscript.exe
as the scheduled command, and put the full path and name of the script file, in quotation marks, as the first argument.
9. Review the task on the Summary screen. If you want to set advanced options such as idle time, what to do if the computer is running on batteries, and what to do after the task completes, check Open Properties Dialog for This Task When I Click Finish. Click Finish to complete the task.
For more advanced scheduling, use the Create Task selection. The Create Task interface uses a multitabbed interface instead of a wizard. The General tab includes security options, whereas the Triggers tab permits you to specify multiple triggers for a task (the task will be performed whenever any of the triggers occurs). The Actions tab supports multiple actions in a task; the Conditions tab includes options to configure idle time, power, and network connection requirements; and the Settings tab supports conditions for running and stopping a task. Use Create Task, rather than Create Basic Task, when you need these additional settings in your task.
3.144.16.151