Windows Vista : Scripting and Automation - Command Prompt Scripting (part 3)

9/26/2012 1:58:23 AM

6. Conditional Statements

There are three versions of the if statement, which allow you to compare values and check the existence of files. The first version, which is usually used to test the value of a variable, is used as follows:

if "%1"=="help" goto SkipIt

Note the use of quotation marks around the variable name and the help text, as well as the double equals signs, all of which are necessary here. Notice also there's no then keyword, which those of you who are familiar with VBScript might expect. If the batch file finds that the two sides are equal, it executes everything on the right side of the statement; in this case, it issues the goto command.

The second use of the IF command is to test the existence of a file:

if exist c:\windows\tips.txt goto SkipIt

If the file C:\Windows\tips.txt exists, the goto command will be executed. Similarly, you can you can test for the absence of a file, as follows:

if not exist c:\autoexec.bat goto SkipIt

The third use of the if command is to test the outcome of the previous command, as follows:

if errorlevel 0 goto SkipIt

If there was any problem with the statement immediately before this line, the errorlevel (which is similar to a system-defined variable) will be set to some nonzero number. The if statement shown here tests for any errorlevel that is greater than zero; if there was no error, execution will simply continue to the next command.

if "%1"=="" goto problem
if "%2"=="" goto problem
if not exist %1 goto problem
if not exist %2 goto problem
fc %1 %2 >c:\windows\temp\output.txt
if errorlevel 0 goto problem
if not exist c:\windows\temp\output.txt goto problem
notepad c:\windows\temp\output.txt
echo "There's a problem; deal with it."

This batch file is essentially the same as the original two-line example shown earlier, except that some error-checking if statements have been added to make the batch file a little more robust. If you neglect to enter one or both command-line parameters, or if the files you specify as command-line parameters don't exist, the batch file will display the error message. An even more useful version might have multiple error messages that more accurately describe the specific problem that was encountered.

7. Loops

Batch files have a very simple looping mechanism, based loosely on the loop used in other programming languages. The main difference is that the batch file for loop doesn't increment a variable regularly, but rather cycles it through a list of values. Its syntax is as follows:

for %%i in ("Abe","Monty","Jasper") do echo %%i

Here, the variable syntax gets even more confusing; the reference to the i variable when used in conjunction with the statement gets two percent signs in front of the variable name and none after. Note also that only single-letter variables can be used here.

If you execute this batch file, you'll get the following output:


Note also the use of the quotation marks; although they aren't strictly necessary, they're helpful if one or more of the values in the list has a comma in it.

To simulate a more traditional For...Next statement in a batch file, type the following:

for %%i in (1,2,3,4,5) do echo %%i

8. Simulating Subroutines

Batch files have no support for named subroutines . However, you can simulate subroutines by creating several batch files: one main file and one or more subordinate files (each of which can accept command-line parameters). You probably wouldn't want to use this if performance is an issue.

This is useful in cases like the statement (described in the proceeding section), which can only loop a single command.

In one batch file, called WriteIt.bat, type:

if "%1"=="" exit
if exist %1.txt del %1.txt
echo This is a text > %1.txt

Then, in another batch file, called Main.bat, type the following:

for %%i in ("Kang","Kodos","Serak") do call WriteIt.bat %%i

The single-line Main.bat batch file uses the call command to run the other batch file, WriteIt.bat, three times. You could omit the call command, but doing so would cause the whole process to end after the subordinate batch file was run the first time. Don't ask me why.

When this pair of batch files is run, you should end up with three files, Kang.txt, Kodos.txt, and Serak.txt, all containing the text, "This is a text." The if statement and the loop are explained in earlier sections.

9. Get to the Command Prompt Quickly

If you find yourself using the Command Prompt frequently, you'll probably benefit from the following solution. Instead of having to use the cd command to change to a given folder, you can simply open a Command Prompt window on the fly in Explorer, already rooted in the selected folder.

  1. Open the Registry Editor .

  2. Expand the branches to HKEY_CLASSES_ROOT\Directory\shell. 

  3. Create a new key by going to Edit → New → Key, and type cmd for the name of this new key.

  4. Double-click the (default) value in the new cmd key, and type the following for its contents:

    Open Command &Prompt Here

  5. Next, create a new key here by going to Edit → New → Key, and type command for the name of the new key.

  6. Double-click the (default) value in the new command key, and type the following for its contents:

    cmd.exe /k "cd %L && ver"

    This line launches the cmd.exe application, and then, using the /k parameter, instructs it to carry out these two commands:

    cd %1

    which change the working directory to the folder that has been right-clicked, and then displays the Windows version, respectively.

  7. Close the Registry Editor when you're done; the change will take effect immediately. Just right-click any folder and select Open Command Prompt Here to open a Command Prompt window at the selected folder.

A simpler (and somewhat slicker) solution is to use Creative Element Power Tools ( Once you turn on the Open a Command Prompt in any folder option, you can right-click any folder icon or the background of any open folder window (or the desktop), and select Command Prompt to open a new Command Prompt window rooted at the selected folder. The tool can also be configured to open the Windows PowerShell (covered next), or any third-party Command Prompt application.

  •  Windows Vista : Scripting and Automation - Wacky Script Ideas
  •  Windows 7 : Programming Drivers for the User Mode Driver Framework - Required Driver Functionality, UMDF Sample Drivers
  •  Windows 7 : Programming Drivers for the User Mode Driver Framework - Windows I/O Overview, Brief COM Information, UMDF Architecture
  •  Installing Windows Small Business Server 2011 (part 2) - Understanding the Installation Process
  •  Installing Windows Small Business Server 2011 (part 1) - Performing a Clean Windows SBS 2011 Installation
  •  Preparing Your Windows 8 PC : Connecting to Wireless Networks
  •  Preparing Your Windows 8 PC : Setting App Notifications - Changing Notifications
  •  Gainward Geforce GTX 690 4GB For The Most Dedicated Gamers
  •  Portable Drive Algato Thunderbolt SSD
  •  Laptop HD Pavillion DM1 - 3200SA - The Thinnest Ultraportables
    Top 10
    New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
    SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
    The latest Audi TT : New angles for TT
    Era of million-dollar luxury cars
    Game Review : Hearthstone - Blackrock Mountain
    Game Review : Battlefield Hardline
    Google Chromecast
    Keyboards for Apple iPad Air 2 (part 3) - Logitech Ultrathin Keyboard Cover for iPad Air 2
    Keyboards for Apple iPad Air 2 (part 2) - Zagg Slim Book for iPad Air 2
    Keyboards for Apple iPad Air 2 (part 1) - Belkin Qode Ultimate Pro Keyboard Case for iPad Air 2
    - First look: Apple Watch

    - 3 Tips for Maintaining Your Cell Phone Battery (part 1)

    - 3 Tips for Maintaining Your Cell Phone Battery (part 2)
    Popular Tags
    Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone