Monday, 30 June 2014

Managing Windows Systems with Command

Managing Windows Systems

As an administrator, it’s your job to plan, organize, and track the details that keep the network running. If you’re to survive without just muddling through, you need to learn how to do those jobs quickly and efficiently. Fortunately, Windows supplies plenty of command-line tools to help you with these tasks and this chapter discusses some of the more important tools for daily systems management.

Examining System Information

Often when you are working with a user’s computer or a remote server, you’ll want to examine some basic system information, such as who is logged on, the current system time, or the location of a certain file. Commands that help you gather basic system information include
  • NOW  Displays the current system time and date using a 24-hour clock, such as Sat May 9 12:30:45 2003. Available in the Windows Server 2003 Resource Kit only.
  • WHOAMI  Displays the name of the user currently logged on the system, such as adatum\administrator.
  • WHERE  Searches for files using a search pattern and returns a list of matching results.
To use NOW or WHOAMI, simply type the command in a command shell window and press Enter. With WHERE, the most common syntax you’ll use is
where /r baseDir filename
Here, /r is for a recursive search starting from the specified directory (\BaseDir) and including all subdirectories, and filename is the name or partial name of the file to search for, which can include wildcards. Use ? as a wildcard to match a single character and * as a wildcard to match multiple characters, such as data???.txt or data*.*. In the following example, you search the C:\ directory and all subdirectories for text files that begin with data, as follows:
where /r C:\ data*.txt
You can also search for files of all types that begin with data, as in this example:
where /r C:\ data*.*
Sometimes when you are working with a computer, you’ll want to obtain information on the system configuration or the system environment. With mission-critical systems, you may want to save or print this information for easy reference. Commands that help you gather system information include
  • DRIVERQUERY  Displays a list of all installed device drivers and their properties, including module name, display name, driver type, and driver link date. With verbose output, the command also lists the driver status, state, start mode, memory usage, and file system path. Use the /V parameter to get verbose output of all unsigned drivers.
  • SYSTEMINFO  Displays detailed system configuration information, including operating system version, system type, system manufacturer, processor, BIOS version, memory size, local setting, time zone setting, and network card configuration.
  • NLSINFO  Displays detailed locale information, including default language, system locale, windows code page, time and number formats, time zone, and installed code pages. Available in the Windows Server 2003 Resource Kit only.
To use these commands on a local computer, simply type the command name in a command shell window and press Enter. With DRIVERQUERY, use the /V parameter to get verbose output and the /Si parameter to display properties of signed drivers, such as
driverquery /v /si
With the DRIVERQUERY and SYSTEMINFO commands, you can also specify the remote computer to query and the Run As permissions. To do this, you must use the expanded syntax, which includes the following parameters:
/S Computer /U [Domain\]User [/P Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account whose permissions you want to use, and Password is the optional password for the user account. If you don’t specify the domain, the current domain is assumed. If you don’t provide the account password, you are prompted for the password.
To see how the computer and user information can be added to the syntax, consider the following examples:
Use the account adatum\wrstanek when querying MAILER1 for driver settings:
driverquery /s mailer1 /u adatum\wrstanek
Use the account adatum\administrator when querying CORPSERVER01 for system information:
systeminfo /s corpserver01 /u adatum\administrator
Tip 
The basic output of these commands is in table format. You can also format the output as a list or lines of comma-separated values using /Fo List or /Fo Csv, respectively. You may wonder why you should use the various formats. That’s a good question. I recommend using the verbose list format (/Fo List /V) when you want to see all details about tasks configured on a system and when you are troubleshooting. I recommend using comma-separated values when you want to store the output in a file that may later be exported to a spreadsheet or flat-file database. Remember you can redirect the output of the DRIVERQUERY and SYSTEMINFO commands to a file using output redirection (> or >>).

Scheduling Tasks with Schtasks

Scheduling Tasks with Schtasks

With Schtasks, you can perform the same task scheduling operations as with the Scheduled Task Wizard. Any tasks you create using Schtasks are displayed as scheduled tasks in the Scheduled Tasks folder and can be managed from the command line or from the graphical user interface (GUI).
Schtasks has several different sets of subcommands and is one of the more complex utilities available at the command line. The sections that follow discuss each of the following subcommands:
  • Schtasks /Create  Used to create scheduled tasks
  • Schtasks /Change  Used when you want to change the properties of existing tasks
  • Schtasks /Query  Used to display scheduled tasks on the local or named computer
  • Schtasks /Run  Used to start a scheduled task immediately
  • Schtasks /End  Used to stop a running task
  • Schtasks /Delete  Used to remove scheduled tasks that are no longer wanted

Creating Scheduled Tasks with Schtasks /Create

With Schtasks /Create, you can create one-time-only tasks, recurring tasks, and tasks that run based on specific system events, such as logon and startup. The basic syntax for defining these types of tasks is as follows:
schtasks /create /tn TaskName /tr TaskToRun /sc ScheduleType [/mo
Modifier]
where TaskName sets the task name string, TaskToRun specifies the file path to the command-line utility or script that you want to run, ScheduleType specifies the run schedule, and Modifier is an optional value that modifies the run schedule based on the schedule type. Any tasks you create using this syntax are created on the local computer and use your user permissions. Further, if you don’t provide your account password, you are prompted for your user password when you create tasks.
Valid values for ScheduleType are shown in Table 4-1. Note the usage and modifiers that the various schedule types accept. We will discuss each schedule type and modifier in detail later in the chapter. Note the following as well:
Table 4-1: Schedule Types for Schtasks /Create
Schedule Type
Description
Modifier Values
MINUTE
Task runs at a specified interval in minutes. By default, tasks run once a minute.
/mo 1-1439; the number of minutes between each run of the task. The default modifier is 1.
HOURLY
Task runs at a specified interval in hours. By default, tasks run once an hour.
/mo 1-23; the number of hours between each run of the task. The default modifier is 1.
DAILY
Task runs every day or every N days. By default, tasks run once a day.
/mo 1-365; the number of days between each run of the task. The default modifier is 1.
WEEKLY
Task runs every week or every N weeks, on designated days. By default, tasks run once a week on Mondays.
/mo 1-52; the number of weeks between each run of the task. Optionally, use /d to specify the days of the week to run. Use MON, TUE, WED, THU, FRI, SAT, and SUN to specify days. * for every day of the week.
MONTHLY
Task runs every month or every N months on designated days. By default, tasks run the first day of every month.
/mo 1-12; the number of months between each run of the task. Optionally, use /d MON-SUN; sets day of the week to run during the month. Use * to have the task run every day.
 
2nd monthly variant for specific day of month. Use /mo and /m, or /m and /d.
/mo LASTDAY; last day of month
/m JAN, FEB, ..., DEC; sets the month(s).
/d 1-31; day of month
 
3rd monthly variant for specific week of the month.
/mo FIRST | SECOND | THIRD | FOURTH | LAST; sets week of month.
/d MON-SUN; sets day of week./m JAN, FEB, ..., DEC; sets month(s).
ONCE
Task runs once at a specified date and time.
ONSTART
Task runs whenever the system starts.
ONLOGON
Task runs whenever a user logs on.
ONIDLE
Task runs whenever the system is idle for a specified period of time.
/i 1-999; the number of minutes the system has to be idle before the task starts.
  • Days of the week can be entered in a comma-separated list, such as Mon, Wed, Fri, or with a hyphen to specify a sequence of days, such as Mon-Fri for Monday through Friday.
  • Months of the year can be entered in a comma-separated list, such as Jan, Mar, Jun, or with a hyphen to specify a sequence of months, such as Jan-Jun for January through June.
  • With week of the month, you can only enter one value, such as FIRST or LAST.
To see how Schtasks /Create can be used, consider the following examples:
Task runs once immediately and then doesn’t run again:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc once
Task runs when the system starts:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onstart
Task runs whenever the system is idle for more than 10 minutes:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onidle
/i 10
Task runs every 15 minutes on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc minute
/mo 15
Task runs every five hours on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc hourly
/mo 5
Task runs every two days on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc daily
/mo 2
Task runs every two weeks on Monday (the default run day):
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly
/mo 2
Task runs every week on Monday and Friday:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly
/d mon,fri
Task runs on the first day of every month:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc monthly
Task runs on the fifth day of every other month:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc monthly
/mo 2 /d 5
Task runs the last day of every month:
schtasks /create /tn "SysChecks" /tr c:\scripts\sysch.bat /sc
monthly/mo lastday
Task runs the first Monday of April, August, and December:
schtasks /create /tn "SysChecks" /tr c:\scripts\sysch.bat /sc
monthly /mo first /d mon /m apr,aug,dec
When the path of the specified task includes a space, enclose the file path in double quotation marks as shown in the following example:
schtasks /create /tn "SysChecks" /tr "c:\My Scripts\sch.bat" /sc
onstart
If you do not enclose the file path in quotation marks, an error will occur when Schtasks attempts to run the task. Further, if you want to pass arguments to a program, utility or script, simply follow the Task To Run file path with the arguments you want to use. Any argument that contains spaces should be enclosed in quotation marks so that it is properly interpreted as a single argument rather than multiple arguments. Here are examples:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat 1 Y LAST /sc
onstart
schtasks /create /tn "SysChecks" /tr "c:\My Scripts\sch.bat" Y N /sc
onstart
schtasks /create /tn "SysChecks" /tr "c:\My Scripts\sch.bat" "Full
Checks"
You can also schedule tasks for remote computers as well as tasks that should run with different user permissions. The key detail to remember when scheduling tasks on remote computers is that the computer you are using should be in the same domain as the remote computer or in a domain that the remote computer trusts. To do this, you must use the expanded syntax which includes the following parameters:
/s Computer /u [Domain\]User [/p Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account whose permissions you want to use, and Password is the optional password for the user account. If you don’t specify the domain, the current domain is assumed. If you don’t provide the account password, you are prompted for the password.
Tip 
If you want a task to run only when a specific user is logged on, use the optional /It parameter, which specifies that the task should run only when the user who owns the task is logged on. The /It parameter is only valid for Windows Server 2003. It cannot be used with Windows XP.
To see how the computer and user information can be added to the syntax, consider the following examples:
Use the account adatum\wrstanek when setting permissions for the task on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onstart
/s mailer01 /u adatum\wrstanek
Set the remote computer as mailer01 and the account to use as adatum\wrstanek:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onstart
/s mailer01 /u adatum\wrstanek
Finally, if desired, you can add specific start times and dates, as well as end times and dates, using
  • /st StartTime, where StartTime is in 24-hour clock format (HH:MM), such as 15:00 for 3 P.M.
  • /et EndTime, where EndTime is in 24-hour clock format (HH:MM), such as 15:00 for 3 P.M. Used only with /sc minute and /sc hourly. Applies to Windows Server 2003 only.
  • /du Duration, where Duration is the number of hours and minutes to run, in the form HHHH:MM. Used only with /sc minute and /sc hourly. Applies to Windows Server 2003 only.
  • /sd StartDate, where StartDate is the start date using the default system format for dates, such as MM/DD/YYYY.
  • /ed EndDate where EndDate is the end date using the default system format for dates, such as MM/DD/YYYY.
Tip 
If you specify an end date or time, you can also specify the /Z parameter, which tells the Task Scheduler to delete the task upon completion of its schedule. This applies only to Windows Server 2003.
To see how specific start times and dates, as well as end times and dates, can be used, consider the following examples:
Start the hourly task at midnight:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc hourly
/st 00:00
Start the hourly task at 3 A.M. and stop it at 7 A.M.:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc hourly
/st 03:00 /et 07:00
Start the weekly task at 3 A.M. on February 20, 2004:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly
/st 03:00 /sd 02/20/2004
Start the weekly task at 3 A.M. on February 20, 2004 and end at 2:59 A.M. on March 15, 2004:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly
/st 03:00 /sd 02/20/2004 /et 02:59 /ed 03/15/2004
Note 
Date and time formats are determined by the Regional And Language options settings used by the computer. In these examples, the date format preference is English (United States).

Changing Scheduled Tasks with Schtasks /Change

You use Schtasks /Change to change key parameters associated with scheduled tasks. The basic syntax of Schtasks /Change is
schtasks /change /tn TaskName ParametersToChange
where TaskName is the name of the task you want to change and Parameters-
ToChange are the parameters you want to change. Parameters you can work with include

  • /ru Domain\User changes the user to run the task as, such as /ru adatum/ wrstanek.
  • /rp Password sets the password for the previously specified or newly designated run as user account.
  • /tr TaskToRun changes the command-line utility or script that is run for the named task.
  • /st StartTime sets the start time for minute or hourly tasks. This applies to Windows Server 2003 only.
  • /ri Interval sets the run interval in minutes. This applies to Windows Server 2003 only.
  • /et EndTime sets the end time for minute or hourly tasks. This applies to Windows Server 2003 only.
  • /du Duration sets the number of hours and minutes to run the task. Minute and hourly tasks only. This applies to Windows Server 2003 only.
  • /sd StartDate sets the start date for the task. This applies to Windows Server 2003 only.
  • /ed EndDate sets the end date for the task. This applies to Windows Server 2003 only.
  • /k specifies that the task should not be started again when the end time or duration interval is reached, but it doesn’t stop the task if it is already running (the current run will be the last one). This applies to Windows Server 2003 only.
  • /it specifies that the task should run only when the user who owns the task is logged on. This applies to Windows Server 2003 only.
To see how you can change tasks, consider the following examples:
Change the script that is run:
schtasks /change /tn "SysChecks" /tr c:\scripts\systemchecks.bat
Change the run as user and password:
schtasks /change /tn "SysChecks" /ru adatum\hthomas /rp gophers
Change task to start weekly at 7 A.M. on March 1, 2004 and end at 6:59 A.M. on March 30, 2004:
schtasks /change /tn "SysChecks" /st 07:00 /sd 03/01/2004 /et 06:59
/ed 03/30/2004
Note 
As mentioned previously, date and time formats are determined by the Regional And Language options settings used by the computer. Here, the date format is English (United States).
When you change a task, Schtasks displays a message that states whether the changes succeeded or failed, such as
SUCCESS: The parameters of the scheduled task "SysChecks" have been
changed.
If you are working with a remote computer or aren’t logged in with a user account that has permission to change the task, you can specify the computer and account information as necessary. The syntax is
schtasks /change /tn TaskName /s Computer /u [Domain\]User [/p
Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account whose permissions you want to use, and Password is the optional password for the user account. If you don’t specify the domain, the current domain is assumed. If you don’t provide the account password, you are prompted for the password.
In the following example, the remote computer is mailer1 and the user account that has authority to change the SysChecks task is wrstanek’s Adatum domain account:
schtasks /change /tn "SysChecks" /tr c:\scripts\systemchecks.bat
/s mailer01 /u adatum\wrstanek
Because a password isn’t specified, Schtasks will prompt for one. In Windows Server 2003 only, you can also quickly enable or disable tasks by name. Use the following syntax to enable tasks:
schtasks /change /tn TaskName /enable
Use this syntax to disable tasks:
schtasks /change /tn TaskName /disable
where TaskName is the name of the task you want to enable or disable, such as
schtasks /change /tn "SysChecks" /disable

Querying for Configured Tasks with Schtasks /Query

You can quickly determine what tasks are configured on a computer by typing schtasks query at the command prompt and, as necessary for a remote computer, you can specify the computer and the account information needed to access the computer using the form:
schtasks /query /s Computer /u [Domain\]User [/p Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account with appropriate access permissions on the remote computer, and Password is the optional password for the designated user account.
In the following example, the remote computer is mailer1 and the user account is wrstanek’s Adatum domain account:
schtasks /query /s mailer01 /u adatum\wrstanek
Because a password isn’t specified, Schtasks will prompt for one.
The basic output of Schtasks /Query is in table format and provides TaskName, Next Run Time, and Status columns. You can also format the output as a list or lines of comma-separated values using /Fo List or /Fo Csv, respectively. The list output works best with the /V (verbose) parameter, which provides complete details on all task properties and which can be used as shown in the following example:
schtasks /query /s mailer01 /u adatum\wrstanek /fo list /v
Another parameter that is useful is /Nh, which specifies that table- or CSV- formatted output should not have headings.
Tip 
You may wonder why you’d want to use the various formats. It’s a good question. I recommend using the verbose list format (/Fo List / V) when you want to see all details about tasks configured on a system and when you are troubleshooting, and I recommend using comma-separated values when you want to store the output in a file that may later be exported to a spreadsheet or flat-file database. Remember you can redirect the output of Schtasks to a file using output redirection (> or >>).

Running Tasks Immediately with Schtasks /Run

You can run a task at any time using
schtasks /run /tn TaskName
where TaskName is the name of the task you want to run, such as
schtasks /run /tn "SysChecks"
Running a task does not affect its schedule and does not change the next run time for the task. If the task can be successfully started, you should see a message stating so. Additionally, you can specify the name of the remote computer on which the task is configured and as necessary the account to run the task as, including an optional password. Here are examples:
schtasks /run /tn "SysChecks"/s 192.168.1.100
schtasks /run /tn "SysChecks"/s 192.168.1.100 /u adatum/wrstanek
Note 
If you specify a user and don’t provide a password, you will be prompted immediately to enter the password.

Stopping Running Tasks with Schtasks /End

You can stop a task at any time using
schtasks /end /tn TaskName
where TaskName is the name of a task that is currently running and should be stopped, such as
schtasks /end /tn "SysChecks"
The task is only stopped if it is running and if successful, the output message should be similar to the following:
SUCCESS: The scheduled task "SysChecks" has been terminated
successfully.
You can also specify the name of the remote computer on which the task is configured and as necessary the account with authority to stop the task, including an optional password, such as:
schtasks /end /tn "SysChecks"/s 192.168.1.100
Or
schtasks /end /tn "SysChecks"/s 192.168.1.100 /u adatum/wrstanek
Because a password isn’t specified, Schtasks will prompt for one.

Deleting Tasks with Schtasks /Delete

You can delete tasks by name on local and remote computers using the syntax
schtasks /delete /tn TaskName [/s Computer /u [Domain/]User [/p
Password]]
where TaskName is the name of a task that should be deleted and the rest of the parameters optionally identify the remote computer, the user account to use when deleting the task and the password for the account, such as
schtasks /delete /tn "SysChecks"
or
schtasks /delete /tn "SysChecks"/s 192.168.1.100 /u adatum/wrstanek
/p frut5
Note 
If you specify a user name and don’t provide a password, you will be prompted immediately to enter the password.
After entering the Schtasks /Delete command, you should see a warning asking you to confirm that you want to remove the task. Press the appropriate letter on your keyboard. If you don’t want to see a warning prompt use the /f parameter, such as
schtasks /delete /tn "SysChecks" /f
Here, you force Schtasks to delete the task without a warning.
In addition, if you want to delete all scheduled tasks on the local computer or the specified remote computer, enter asterisk (*) as the task name, such as
schtasks /delete /tn *
Confirm the action when prompted.

CMD Scheduling Tasks on Local and Remote Systems

Scheduling Tasks on Local and Remote Systems

Whatever you can execute at the command line can be configured as a scheduled task, including command-line utilities, scripts, applications, shortcuts, and documents. You can also specify command-line arguments. At times when you schedule tasks, you’ll do so for the computer to which you are currently logged on (that is, a local system). More typically, however, when you schedule tasks you’ll do so for remote systems throughout your network from your local computer (that is, a remote computer).

Introducing Task Scheduling

The following Windows features work together to enable local and remote task scheduling:
  • Task Scheduler  The Windows service that controls task scheduling. This service must be running for each system on which you want to schedule tasks. Task Scheduler logs on as the LocalSystem account by default and usually doesn’t have adequate permissions to perform administrative tasks. Because of this, you should configure each task individually to use an account with adequate user privileges and access rights to run the tasks you want to schedule. You should also make sure that the Task Scheduler service is configured to start automatically on all the systems for which you want to schedule tasks. Be sure to set the Task Scheduler startup and logon account options appropriately.
  • File And Printer Sharing For Microsoft Networks  The Windows networking component that allows other computers to access resources on a system. This component must be installed and enabled on each system that you want to access and control remotely through the task scheduler. It also enables many other remote-management functions.
Note 
Errors that you may see if the File And Printer Sharing For Microsoft Networks component isn’t installed or enabled include “RPC Server unavailable” and “Network path not found.” See the section in Chapter 16 titled “Configuring Additional Networking Components” in Microsoft Windows Server 2003 Administrator’s Pocket Consultant (Microsoft Press, 2003), for details on installing and configuring networking components.
         Each scheduled task runs only one program, utility, or script, and can be configured to run
  • At a specific time and date, such as at 5:45 P.M. on October 25, 2004
  • At a specified interval, such as every Monday, Wednesday, and Friday at 5:45 P.M.
  • When a specific system event occurs, such as when someone logs on to the system
Event-based tasks deserve special attention because they don’t always work as you might expect and include tasks triggered by
  • System Start  If you schedule a task to run when the system starts, Task Scheduler runs the task as a noninteractive process whenever the computer is started. The task will continue to run until it finishes, is terminated, or the system is shut down. Keep in mind that only the owner of the task or an administrator can terminate running tasks.
  • System Logon  If you schedule a task to run when a user logs on, Task Scheduler runs that task whenever anyone logs on (regardless of who configured the task to run), and continues to run until it finishes, is terminated, or the user logs off. Logon tasks can run interactively or noninteractively, depending on how they are configured.
    Tip 
    If a user configures an interactive task using his or her logon and someone else logs on, the task runs with the original user’s permissions and may not terminate when the other user logs off (because it is owned by someone else and the current user may or may not have appropriate permissions to terminate the task). Further, with Fast User Switching on Windows XP, logon tasks do not run when you switch users. Logon tasks only run when someone logs on while all users are logged off.
  • System Idle  If you schedule a task to run when the system is idle, Task Scheduler runs the task whenever there is no user activity for a specified amount of time. For example, you might create a task that runs only when the system has been idle for five minutes. Keep in mind, however, that subsequent user activity will not terminate the task. The task will continue to run until it finishes or is terminated.
To run multiple commands, programs, and utilities, you can create a command- line script that performs the necessary tasks. Here, you’ll want the script to run with specific user or administrator credentials to ensure that the script has the necessary permissions and access rights. The script should also configure whatever user settings are necessary to ensure that everything it does is under its control and that domain user settings, such as drive mappings, are available as necessary.
Real World 
When you configure tasks to run, you can specify the user account and logon password to use when the task runs. With recurring tasks, this tactic can lead to problems, especially if permissions or passwords change—and they inevitably do. If account permissions or passwords change, you’ll need to edit the task’s properties and supply the new logon credentials for the account.

Accessing and Scheduling Tasks

Any user can schedule a task on the local computer, and they can view and change the tasks that they’ve scheduled. Administrators can schedule, view, and change all tasks on the local computer. To schedule, view, or change tasks on remote computers, you must be a member of the Administrators group on the remote computer, or you must be able to provide the credentials of an Administrator of the remote computer when prompted.
Regardless of whether you use the Scheduled Task Wizard or Schtasks, you can access and manage a system’s tasks using the Scheduled Tasks folder, which you can think of as your central interface for task scheduling. You can access the Scheduled Tasks folder on a local system with either of the following techniques:
  • Start Control Panel and then click Scheduled Tasks.
  • Start Windows Explorer, click My Computer, then Control Panel, and then Scheduled Tasks.
In a Windows domain, you can access the Scheduled Tasks folder on a remote system by completing the following steps:
  1. Start Windows Explorer, then use the My Network Places node to navigate to the computer you want to work with.
  2. Click the computer’s icon, and then click Scheduled Tasks, as shown in Figure 4-1.

    Figure 4-1: The Scheduled Tasks folder shows any tasks currently configured on the system by name, run time, and status.

Real World 
In a workgroup, the easiest way to access the Scheduled Tasks folder on a remote system is to use a Remote Desktop connection. You also can use this technique for computers in a domain, of course, but it isn’t necessary. In either case, you must first ensure that the Allow Users To Connect Remotely To This Computer check box is selected on the Remote tab of the System utility in Control Panel. Next, set up a remote desktop connection by performing the following steps:
  1. Click Start, Programs or All Programs, Administrative Tools, and finally Remote Desktops. This starts the Remote Desktops console.
  2. Right-click Remote Desktops below the Console Root in the left pane and then select Add New Connection.
  3. Type the computer name or IP address of the workgroup or domain computer you wish to access and the user name and logon information, and then click OK.
    For a workgroup computer, you use a user account that is on the computer you are accessing. Afterward, connect to the computer using the Remote Desktop connection by right-clicking the connection and selecting Connect. Now start Windows Explorer on the remote computer and navigate to the Scheduled Tasks folder.     
                                                 Figure 4-1 that the Scheduled Tasks folder shows
  • Name  The name of the task. Task names can be any string of characters and, like other task properties, are set when you create the task.
  • Schedule  The run schedule of the task. “Disabled” means that task has been disabled and will not run.
  • Next Run Time  The next date and time the task will run. “Never” indicates the task will not run again after the scheduled run time and is probably a one-time task.
  • Last Run Time  The last date and time the task ran. “Never” indicates the task has not run for the first time.
  • Status  The current status of the task. “Running” indicates the task has been started by the task scheduler and is running. “Could not start” indicates the task could not be started and that there is a problem with the task.
  • Last Result  The exit error code. An error code of zero indicates no error occurred. Any other value indicates some type of error occurred.
  • Creator  The user name of the person who created the scheduled task.

Monitoring Scheduled Tasks

The Task Scheduler service doesn’t verify the information you provide or the availability of programs, commands, or utilities. If you don’t specify the correct information, the task simply won’t run or will generate errors when it does run. One way to check tasks is to view their status and last result in the Scheduled Tasks folder. This information pertains to the last time the scheduled task ran. It won’t tell you, however, if there were problems running tasks prior to the last run time. To dig deep and get a better understanding of how tasks are running, you should periodically check the Task Scheduler log file, Schedlgu.txt, located in the %SystemRoot%/Tasks folder.
You can examine the log file by selecting View Log from the Advanced menu when the Scheduled Tasks folder is selected in Windows Explorer. If you examine the task scheduler log, you’ll find
  • Entries that record when the Task Scheduler Service was started and when the service exited (was stopped).
  • Entries that record when tasks are started, when they finished running, and the exit error code. An exit error code of zero (0) means that the task executed normally. Any other exit code indicates an error may have occurred.
Note   
   %SystemRoot%\Tasks is a special folder with a view that allows you to work with scheduled tasks. If you access this folder in Windows Explorer, you won’t see the SchedLgU.txt log. It is there, however, and if you access the related directory from the command prompt—by changing the directory to %SystemRoot%\Tasks—you’ll see the log in the listing.
You may also want a more detailed understanding of what happens when scripts run. To do this, you may want to record the output of commands and utilities in a separate log file, thereby giving you the opportunity to determine that those commands and utilities produced the expected results. As discussed in the previous chapter, you can write command output to a named file by redirecting standard output and standard error. In the following examples, the output of the DEFRAG command is appended to Stat-log.txt and any DEFRAG errors are written to this file as well:

defrag c: >> c:\logs\stat-log.txt 2>&1
defrag d: >> c:\logs\stat-log.txt 2>&1
Caution 
If you are working with a directory, as shown in these examples, the directory must already exist. It will not be created for you, and any errors resulting from the lack of a directory will not be written to the log file.

Real World 
Writing command output to a log file won’t help you resolve every problem that can occur, but it goes a long way toward ensuring that scheduled tasks run as expected. If you are trying to troubleshoot problems, keep in mind that tasks can fail to run for many reasons, some of which are beyond your control. For example, scheduled tasks won’t run if the system is shut down when the task is scheduled to run. If you want to be notified when tasks are missed, select Notify Me Of Missed Tasks from the Advanced menu when the Scheduled Tasks folder is selected in Windows Explorer. With this feature enabled, a message is displayed when you log on that tells you if you missed a task because the system was shut down.

Saturday, 28 June 2014

Command Line Iteration Statements

Command Line Iteration Statements

When you want to execute a command or a series of commands repeatedly, you’ll use the for statement. The for statement is a powerful construct, and before you skip this section because you think you know how the for statement works, think again. The for statement is designed specifically to work with the command-shell environment and is very different from any other for statement you may have worked with in other programming languages. Unlike most other for statements, the one in the command line is designed to help you iterate through groups of files and directories, and to parse text files, strings, and command output on a line-by-line basis.

Iteration Essentials

The command shell has several different forms of for statements. Still, the basic form of all for statements is
for iterator do (statement)
Here the iterator is used to control the execution of the for loop. For each step or element in the iterator, the specified statement is executed. The statement can be a single command or multiple commands chained, piped, or grouped within parentheses.
The iterator usually consists of an initialization variable and a set of elements to execute against, such as a group of files or a range of values to step through. Initialization variables are essentially placeholders for the values you want to work with. When you work with initialization variables, keep in mind the following:
  • Iterator variables only exist within the context of a for loop.
  • Iterator variable names must be in the range from a to z or A to Z, such as %%A, %%B, or %%C.
  • Iterator variable names are case-sensitive, meaning %%a is different from %%A.
As Table 3-4 shows, the various structures used with for statements have specific purposes and forms. When the for statement is initialized, iterator variables, such as %%B, are replaced with their actual values. These values come from the element set specified in the for statement and could consist of a list of files, a list of directories, a range of values, and so on.

Table 3-4: Forms for Iteration
Iteration Purpose
Form Syntax
Sets of files
for %%variable in (fileSet) do statement
Sets of directories
for /D %%variable in (directorySet) do statement
Files in subdirectories
for /R [path] %%variable in (fileSet) do statement
Stepping through a series of values
for /L %%variable in (stepRange) do statement
Parsing text files, strings, and command output
for /F [“options”] %%variable in (source) do statement
Real World 
The forms provided are for scripts. You can also use for statements interactively at the command line. In this case, use %variable instead of %%variable. Beyond this, for statements within scripts or at the command line are handled in precisely the same way.

Stepping through a Series of Values

The “traditional” way to use for statements is to step through a range of values and perform tasks using these values. You can do this in the command shell and the basic syntax of this type of for loop is
for /l %%variable in (start,step,end) do (statement)
This type of for statement operates as follows. First, the command shell initializes internal start, step, and end variables to the values you’ve specified. Next, it compares the start value with the end value to determine if the statement should be executed, yielding a true condition if the start value can be incremented or decremented as specified in the step and a false condition otherwise. In the case of a true condition, the command shell executes the statement using the start value, then increments or decrements the start value by the step value specified and afterward, repeats this process. In the case of a false condition, the command shell exits the for statement, moving on to the next statement in the script.
Consider the following example that counts from 0 to 10 by 2’s:
for /l %%B in (0,2,10) do echo %%B
The output is
0
2
4
6
8
10
You can also use a negative step value to move through a range in decreasing values. You could count from 10 to 0 by 2’s as follows:
for /l %%B in (10,-2,0) do echo %%B
The output is
10
8
6
4
2
0

Iterating Through Groups of Files

A more powerful way to use for statements in the command shell is to use them to work with files and directories. The for statement syntax for working with groups of files is
for %%variable in (fileSet) do (statement)
Here you use fileSet to specify a set of files that you want to work with. A file set can be
  • Individual files as specified by a filename, such as MyFile.txt
  • Groups of files specified with wildcards, such as *.txt
  • Multiple files or groups of files with spaces separating file names, such as *.txt *.rtf *.doc
Now that you know the basic rules, working with files is easy. For example, if you want to list all text files in an application directory, you can use the following command in a script:
for %%B in (C:\Working\*.txt) do (echo %%B)
Here B is the initialization variable, C:\Working\*.txt specifies that you want to work with all text files in the C:\Working directory, and the statement to execute is echo %%B, which tells the command shell to display the current value of %%B each time it iterates through the for loop. The result is that a list of the text files in the directory is written to the output.
You could extend this example to examine all .txt, .rtf, and .doc files like this:
for %%B in (%AppDir%\*.txt %AppDir%\*.rtf %AppDir%\*.doc) do (echo
%%B)
You can also use multiple commands using piping, grouping, and chaining techniques, such as
for %%B in (%AppDir%\*.txt %AppDir%\*.rtf %AppDir%\*.doc) do (echo %%B
& move C:\Data)
Here you list the .txt, .rtf, and .doc files in the location specified by the AppDir variable and then move the files to the C:\Data directory.

Iterating Through Directories

If you want to work with directories rather than files, you can use the following for statement style:
for /d %%variable in (directorySet) do (statement)
Here you use directorySet to specify the group of directories you want to work with. Iterating directories works exactly like iterating files, except you specify directory paths rather than file paths. If you wanted to list all the base directories under %SystemRoot%, you would do this as follows:
for /d %%B in (%SystemRoot%\*) do echo %%B
On Windows Server 2003, a partial result list would be similar to
C:\Windows\AppPatch
C:\Windows\Cluster
C:\Windows\Config
C:\Windows\Cursors
C:\Windows\Debug
Note 
Note that the for /d loop iterates through the specified directory set but doesn’t include subdirectories of those directories. To access subdirectories (and indeed the whole directory tree structure), you use for /r loops, which I’ll discuss in a moment.
You can specify multiple base directories by separating the directory names with spaces, such as
for /d %%B in (%SystemRoot% %SystemRoot%\*) do echo %%B
Here you examine the %SystemRoot% directory itself and then the directories immediately below it. So now your list of directories would start with C:\Windows (if this is the system root) and continue with the other directories listed previously.
You can also combine file and directory iteration techniques to perform actions against all files in a directory set, such as
for /d %%B in (%APPDATA% %APPDATA%\*) do (
@for %%C in ("%%B\*.txt") do echo %%C)
The first for statement returns a list of top-level directories under %APPDATA%, which also includes %APPDATA% itself. The second for statement iterates all .txt files in each of these directories. Note the @ symbol before the second for statement. As with if statements, this indicated the second for statement is nested and is required to ensure proper execution. The double quotations with the file set ("%%B\*.txt") ensure that directory and file names containing spaces are handled properly.
Because you’ll often want to work with subdirectories as well as directories, the command shell provides for /r statements. Using for /r statements, you can examine an entire directory tree from a starting point specified as a path. The syntax is
for /r [path] %%variable in (fileSet) do (statement)
Here path sets the base of the directory tree you want to work with, such as C:\. The path is not required, however, and if the path is omitted, the current working directory is assumed.
Using a for /r statement, you could extend the previous example to list all .txt files on the C: drive without needing a double for loop, as shown here:
for /r C:\ %%B in (*.txt) do echo %%B
As you can see, for /r statements are simpler than double for loops and more powerful. You can even combine /r and /d without needing a double loop. In this example, you obtain a listing of all directories and subdirectories under %SystemRoot%:
for /r %SystemRoot% /d %%B in (*) do echo %%B

Parsing File Content and Output

Just as you can work with file and directory names, you can also work with the contents of files and the output of commands. To do this, you’ll use the following for statement style:
for /f ["options"] %%variable in (source) do (statement)
Here, options sets the text matching options, source specifies where the text comes from, which could be a text file, a string, or command output, and statement specifies what commands should be performed on matching text. Each line of text in the source is handled like a record where fields in the record are delimited by a specific character, such as a tab or a space (which are the default delimiters). Using substitution, the command shell then replaces placeholder variables in the statement with actual values.
Consider the following line of text from a source file:
William Stanek Engineering Williams@adatum.com 3408
One way of thinking of this line of text is as a record with five fields:
  • First Name  William
  • Last Name  Stanek
  • Department  Engineering
  • E-Mail Address  Williams@adatum.com
  • Phone Extension  3408
To parse this and other similar lines in the associated file, you could use the following for statement:
for /f "tokens=1-5" %%A in (current-users.txt) do (
@echo Name: %%A %%B Depart: %%C E-mail: %%D Ext: %%E)
Here you specify that you want to work with the first five fields (token fields separated by spaces or tabs by default) and identified by iterator variables, starting with %%A, which means the first field is %%A, the second %%B, and so on. The resulting output would look like this:
Name: William Stanek Depart: Engineering E-Mail: Williams@adatum.com
Ext: 3408
Table 3-5 shows a complete list of options that you can use. Examples and descriptions of the examples are included.
Table 3-5: Options for File Content and Command Output Parsing
Option
Description
Example
Example Description
eol
Sets the end-of-line comment character. Everything after the end-of-line comment character is considered to be a comment.
"eol=#"
Sets # as the end-of-line comment character.
skip
Sets the number of lines to skip at the beginning of files.
"skip=5"
Tells the command shell to skip lines 1 through 5 in the source file.
delims
Sets delimiters to use for fields. The defaults are space and tab.
"delims=,.:"
Specifies that commas, periods, and colons are delimiters.
tokens
Sets which token fields from each source line are to be used. You can specify up to 26 tokens provided you start with a or A as the first iterator variable. By default, only the first token is examined.
"tokens=1,3"
 
"tokens=2-5"
First example sets fields to use as 1 and 3. Second example sets fields 2, 3, 4, and 5 as fields to use.
   
usebackq
Specifies that you can use quotation marks in the source designator: double quotation marks for file names, back quotation marks for command to execute, and single quotation marks for a literal string.
"usebackq"
To see how additional options can be used, consider the following example:
for /f "skip=3 eol=; tokens=3-5" %%C in (current-users.txt) do (
@echo Depart: %%C E-mail: %%D Ext: %%E)
Here, three options are used. The skip option is used to skip the first three lines of the file. The eol option is used to specify the end-of-line comment character as a semicolon (;). Finally, the tokens option specifies that tokens 3 to 5 should be placed in iterator variables, starting with %%C.
With tokens, you can specify which fields you want to work with in many different ways. Here are some examples:
  • tokens=2,3,7  Use fields 2, 3, and 7.
  • tokens=3-5  Use fields 3, 4, and 5.
  • tokens=*  Examine each line in its entirety and do not break into fields.
When you work with text files, you should note that all blank lines in text files are skipped and that multiple source files can be specified with wild cards or by entering the file names in a space-separated list, such as
for /f "skip=3 eol=; tokens=3-5" %%C in (data1.txt data2.txt) do (
@echo Depart: %%C E-mail: %%D Ext: %%E)
If a file name contains a space or you want to execute a command, specify the usebackq option and quotation marks, such as
for /f "tokens=3-5 usebackq" %%C in ("user data.txt") do (
@echo Depart: %%C E-mail: %%D Ext: %%E)
or
for /f "tokens=3-5 usebackq" %%C in (`type "user data.txt"`) do (
@echo Depart: %%C E-mail: %%D Ext: %%E)
Tip 
Remember the backquote (`) is used with commands and the single quotation mark () is used with string literals. In print, these characters no doubt look very similar. However, on a standard keyboard, the backquote (`) is on the same key as the tilde (~) and the single quotation mark () is on the same key as a double quotation mark ().
Note 
In the second example, I use the TYPE command to write the contents of the file to standard output. This is meant to be an example of using a command with the backquote.
Speaking of quotation marks, you use quotation marks when you want to process strings and variable values. Here, you enclose the string or variable name you want to work with in double quotation marks to ensure the string or variable can be evaluated properly. You do not, however, need to use the usebackq option.
Consider the following example:
set value=All,Some,None
for /f "delims=, tokens=1,3" %%A in ("%VALUE%") do (echo %%A %%B)
The output is
All None