Downloads
44894.zip

In "Windows Server 2003 Directory Service Tools," October 2004, InstantDoc ID 43753, I showed you how to manipulate Active Directory (AD) objects from the command line. However, manipulating AD objects is only one aspect of Windows management. Windows 2003 and Windows XP Professional Edition include command-line tools that can save you time and effort in performing repetitive tasks such as creating and managing event logs, configuring the page file and Boot.ini file, managing processes, and determining free disk space. Using command-line tools falls between scripting and the UI and can save you hours writing a script to perform the same tasks. Although you might need a few minutes to determine the exact syntax that each tool needs to use, the time will be well spent. Let's put a few of these tools to work.

Create and Manage Event Logs
Windows 2003 and XP offer three tools to create and manage event logs from the command line: Eventcreate.exe, Eventquery.vbs, and Eventtriggers.exe. Eventcreate allows the creation of events in the Windows NT event log. For example, to create an error event log entry in the application event log, use the following command:

Eventcreate /S vm75459312b.LissWare.Net
  /L application
  /SO "Eventcreate TEST"
  /T Error
  /ID 999
  /D "Event log creation with Eventcreate.exe"

The /S switch specifies the server name. The /L switch specifies the event log to use. The /SO switch specifies the event source name. The /T switch specifies the type of event to create (e.g., success, error, warning, information). The /ID switch specifies the ID number of the event log entry. The /D switch specifies the description of the event log entry. You can also use the /U switch to specify credentials for the Domain\Username and the /P switch to specify the password if a remote system requires credentials other than the current user security context. For more information about available switches and options, use the /? switch.

Now that you've created an event log entry, you can use Eventquery to search for the entry. This tool is written in VBScript so that it can leverage the Windows Management Instrumentation (WMI) features of the Win32_NTEventlogFile class. For example, to locate the event you just created, you would enter the command

C:\>Eventquery /S vm75459312b.LissWare.Net
  /L application
  /FI "type eq Error"

The /S switch specifies the server name, and the /L switch specifies the event log to locate for the query. The /FI switch is specific to Eventquery and specifies the filter to apply to locate the event log entry. In this example, the filter returns event log entries of type error. Of course, the /FI switch accepts other filters. For example, you can locate an event log entry by its type (e.g., success, error, information) and its ID together. The filter combines different criteria, as the following command-line sample, which leverages a logical operator (i.e., AND) shows:

C:\>Eventquery /S vm75459312b.LissWare.Net
  /L application
  /FI "type eq errorAND id eq 999"

As with Eventcreate, you can use the /? switch to see a complete list of switch syntaxes. You can also use the /FO switch to specify the output format (e.g., comma-separated value—CSV—format, table format) and the /V switch to display additional information about the event log entries in verbose mode.

Querying event logs for specific events is interesting, but what's even more interesting is to trigger an action when a specific event log entry is created. You can accomplish this with Eventtriggers. This tool leverages the monitoring capabilities of WMI. Let's say that you want to shut down the system after the event log entry above is created. To do so, you would use the following command:

C:\>Eventtriggers /S vm75459312b.LissWare.Net
  /Create
  /TR "Detect EventCreate"
  /L application
  /T ERROR
  /EID 999
  /TK "Shutdown.exe /S /T 0"

The /S switch specifies the system name, and the /Create switch tells the script to create a new trigger with a name that the /TR switch parameter determines. The /L switch specifies the application event log to filter. The action is triggered only by error event log entries with an event ID of 999, which the /T and /EID switches specify, respectively. You can add the /SO switch to search for the event log entry source name, if necessary. The /TK switch specifies the task to perform, which in this case is a system shutdown performed with the shutdown.exe tool. The tool's /S switch specifies a shutdown, and the /T 0 switch specifies waiting 0 seconds before shutting the system down.

Eventtriggers prompts you for credentials to determine the security context when you execute the shutdown command. Running this command against production systems can cause problems because your systems could shut down frequently if the application event log entries you create match the shutdown command's conditions. To avoid this situation, you can narrow the scope of the query (e.g., by using the /SO switch) and change the trigger conditions to a different event log file, such as the security event log, and a different event log entry type, such as failureaudit. Obviously, you can trigger other actions, such as sending a mail alert or page. The sky is the limit here!

To view the triggers configured in a system, you can use the following command:

C:\>Eventtriggers /S vm75459312b.LissWare.Net /Query

This command lists all triggers with their related tasks. Note that only error, information, warning, successaudit, and failureaudit event log entry types can be tracked—the success event log entry type can't.

Configure the Page File and Boot.ini File
To manage the page-file configuration from the command line, Windows 2003 and XP provide the PageFileConfig.vbs script. This script leverages the features that WMI's Win32_PageFileSetting and Win32_PageFileUsage classes expose. You can modify (/Change switch), add (/Create), and remove (/Delete) entries in a boot.ini file. For example, to modify the page file's initial and maximum size, you can use the following command:

C:\>PageFileConfig /Change /S vm75459312b.LissWare.Net
  /I 512 /M 1024 /VO C:

The /I switch defines the initial size, the /M switch defines the maximum size, and the /VO switch determines the volume name.To create a page file, you can use the /Create switch with the same set of parameters:

C:\>PageFileConfig /Create /S vm75459312b.LissWare.Net
  /I 512 /M 1024 /VO D:

You must reboot to make your changes active. The script will not reboot the system by itself, but you can use the Shutdown tool to reboot from the command line. To view the page-file configuration, use the /Query switch. By default, when no switch is specified, the script performs a query and shows the system's page-file configuration.

To manage Boot.ini from the command line, Windows 2003 and XP include the bootcfg.exe tool. This tool is simple to use. Let's assume that you have a standard Windows 2003 installation. In such a case, Boot.ini contains only one entry, similar to the one that Figure 1 shows. To create a new entry in Boot.ini, execute the following command, which copies the existing entry to a new one:

C:\>Bootcfg /Copy /ID 1  
  /D "Windows Server 2003, Enterprise - EMS BOOT"

The /Copy switch tells the tool to copy the Boot.ini entry that the /ID switch defines (in this case, only one entry is available). The /D switch defines the description you designate for the copied entry. Next, you can use Emergency Management Services (EMS) to enable that new entry. (EMS is a new remote management feature of Windows 2003. You can find more information about EMS at http://www.microsoft.com/resources/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=/Resources/Documentation/windowsserv/2003/all/techref/en-us/w2k3tr_ems_what.asp.) To enable EMS with Bootcfg, use the following command:

C:\>Bootcfg /EMS ON /PORT COM1 /BAUD 19200 /ID 2

The /EMS ON switch activates the EMS feature, and the /PORT switch defines the COM port number to use. The /BAUD switch defines the communication speed for the selected COM port. The /ID switch tells Bootcfg to modify the second entry of the file, which is the one you just created. Run the /? switch to see the options you can use to set up Boot.ini.

Now that you've updated the second entry, you can make it the default entry. To do so, use the /Default switch, as follows:

C:\>Bootcfg /Default /ID 2

Figure 2 shows you the result of using Bootcfg to modify the Boot.ini file. To delete the changes you made, use the /Delete switch with the following command:

C:\>Bootcfg /Delete /ID 1

Note that the switch /ID value is set to 1 now because we previously changed the default entry. Doing so moved the new copied entry from position 2 to position 1 in Boot.ini.

Manage Processes
Windows 2003 and XP let you manage processes from the command line with two tools, Tasklist.exe and Taskkill.exe. Basically, anything you can do by using the graphical task manager interface you can do from the command line with these tools. But don't stop there—you can do a lot more.

If you run Tasklist without any parameters, you'll get a list of all processes running on the system. However, Tasklist exposes switches to perform searches and gather additional information on processes. For example, if you want to view all processes that consume more than 2MB of memory on your system, you can use the /FI switch as follows:

C:\>Tasklist /FI "MEMUSAGE gt 2048"

In this example, the /FI switch defines a filter by using the keyword MEMUSAGE to determine the filtering criteria. Tasklist supports various methods to select and filter processes. For example, you can select a process according to IMAGENAME, SERVICES, or WINDOWTITLE. Selecting a process by its IMAGENAME is simply selecting a process by its name. When you use the /SVC switch, Tasklist lists all Windows service names that run under the selected process. In the same way, when you refer to a Windows service name with the SERVICES keyword, Tasklist will determine which process handles the service. For example, the following command will show you which process handles the remote registry service:

C:\>Tasklist /FI "SERVICES eq RemoteRegistry"

where RemoteRegistry is a service visible in the Microsoft Management Console (MMC) Services snap-in.

For the next example, run two blank instances of Notepad. To list these processes by Window title, use the following command:

C:\>Tasklist /FI "WINDOWTITLE eq untitled - notepad"

Tasklist will show two Notepad process instances because both processes use the same window title.

To kill processes, you use Taskkill and specify the process you want to kill. The selection works the same as for the Tasklist tool with the /FI switch. So, for example, to kill the two blank Notepad instances, run the following command:

 C:\>Taskkill /FI "WINDOWTITLE eq untitled - notepad"

Regarding Taskkill's /IM switch, you can use a wildcard (i.e., *) to specify all process image names (the /IM switch specifies the image name of the process to be terminated). Note that wildcards are accepted only when a filter is specified (i.e., with the /FI switch). Also note that the WINDOWTITLE and STATUS filters aren't functional when you specify a remote machine—these filters work only locally. You can terminate remote processes only by force (i.e., by using the /F switch). Both Tasklist and Taskkill support different filtering techniques and switches to output results in different formats. To see a complete list of available options, launch either tool with the /? switch.

Determine Free Disk Space
Beyond the traditional tasks of managing event log entries, configuration files, and processes, other tasks are more specific to typical day-to-day operations, such as copying files. Evaluating the total file size of a collection of files and making sure enough disk space exists on a target location before executing a copy or move operation can be crucial, particularly if the amount of data you need to copy or move is large. If you don't want to write a WSH script to handle this operation but still want a way to automate the verification, you can combine Cmd.exe statements with two tools available in Windows 2003: Forfiles.exe and Freedisk.exe. Listing 1 shows a sample script that does just that. The Forfiles command within the line at callout A is:

Forfiles.exe /S /M *.DAT /C "Cmd /c echo @fsize"

This line echoes all *.dat file sizes on the screen. The /S switch specifies that the search must be done in the current folder and all subfolders, and the /M switch specifies that all *.dat files be searched. The /C switch defines the command to execute for each file that Forfiles finds. In this case,

"Cmd /c echo @fsize"

simply outputs the size of each found file on the screen.

Placing the Forfiles command inside a For /f statement, as callout A shows, makes it possible to calculate the total size of all *.dat files. The Forfiles invocation is placed between parentheses in the For /f statement, which causes the statement to assign the output of the Forfiles command to the %%i environment variable. The :MakeTotal %%i statement invokes a subroutine called :MakeTotal with a parameter that the %%i variable specifies. The subroutine calculates the total file size with each file that's passed in as a parameter. The total file size is calculated by the Set /A Total=%Total% + %1 statement in the routine. The %1 variable is the first parameter passed during the :MakeTotal call, which is the size of the file examined by the Forfiles tool and stored in the %%i variable during the subroutine call. The For /f statement calls the subroutine for each file size that the Forfiles command returns.

After the For /f statement finishes, the Freedisk tool is executed. Freedisk determines whether the required disk space is available according to two parameters: the disk size required and the size of the target disk. In Listing 1, Freedisk uses the total file size that the Forfiles command calculated and the C:\ disk size determined by the /D switch. Freedisk displays a message stating whether the required disk space is available or not. In the command file, the environment variable %ERRORLEVEL% equals 0 if the necessary space is available or 1 if the space isn't available.

Updated Commands
Some of the new command-line tools in Windows 2003 and XP can be confused with existing commands. For example, Schtasks.exe replaces AT.exe, which previous versions of Windows include. (AT still exists in Windows 2003 and XP, but Microsoft recommends using Schtasks instead.) The aim of both Schtasks and AT is to schedule predefined tasks by leveraging the features that the Task Scheduler Windows Service provides. Schtasks works the way AT does but supports a different set of command-line parameters and syntaxes. Schtasks can do everything the AT command does but also much more. (To work with Schtasks, you must be a member of the Administrators group on the computer that the command affects.) Consider the following Schtasks command:

SCHTASKS /Create /RU Administrator /RP Password1
  /SC MINUTE
  /ST 09:20 /ET 09:30
  /TN "Event Creation"
  /TR "C:\WINDOWS  system32\Eventcreate.exe
  /S vm75459312b.
  LissWare.Net
  /L application
  /SO ScheduledEventCreation
  /T Success
  /ID 999
  /D ScheduledEventLogCreation"

The /TN switch creates a scheduled job named Event Creation. The /SC switch specifies that the job is created every minute between 09:20, which the /ST switch specifies, and 09:30, which the /ET switch specifies. The TR switch specifies that the command to run is an Eventcreate command, with switches and parameters specified between quotation marks. This command will run under the Administrator context, where credentials are passed by means of the /RU and /RP switches. You can't create this type of scheduling with the AT command, at least not easily. Use the /? switch to get more information about options and syntaxes that Schtasks supports.

Gpupdate.exe refreshes Group Policy Objects (GPOs) the way the Secedit.exe /Refreshpolicy command in Windows 2000 does. Gpupdate replaces Secedit in Windows 2003 and XP. However, Gpupdate makes your life easier if you want to refresh a GPO because it doesn't require all the command-line parameters that Secedit does. Use the /? switch to see all the options that Gpupdate supports.

You can use Findstr.exe in Windows 2003 and XP instead of Find.exe. Findstr's purpose is exactly the same as that of Find—both search for a text pattern in a specified path of files. However, Findstr has more searching and filtering capabilities than Find has. Findstr can search a specific list of files and folders and can use regular expressions to filter file content. A regular expression is a special text string that describes a search pattern. (For more information about regular expressions, go to http://www.regular-expressions.info.)

Take Command
I've only scratched the surface of the time- and labor-saving possibilities that the command-line tools in Windows 2003 and XP present. If you want more information about all tools and command-line syntaxes that Windows 2003 and XP support, execute the following command:

C:\>HH.EXE %SystemRoot%\Help\Ntcmds.chm

When you do, you'll discover the command-line jewels that are sleeping in your Windows 2003 and XP installations.



MICROSOFT WANTS YOUR INPUT ABOUT WMI
Like most technologies, Windows Management Instrumentation (WMI) is a work in progress. In its ongoing effort to improve this technology, Microsoft is conducting the WMI Customer Experience survey until the end of February. Here's your chance to tell Microsoft about the features, tools, providers, and classes you find most useful and the features and functionality you'd like added so that Microsoft knows the areas in which to concentrate its improvement efforts. To participate in the WMI Customer Experience survey, go to the following URL:
http://support.microsoft.com/common/survey.aspx?cid=sw;en;1236&p0=&p1=&p2=&p3=&p4.