Tech Tips / Windows NT / Tools and Tasks

Basic scripting techniques

Command scripts are ASCII text files that contain a group of NT commands. Command scripts can help you automate administrative tasks, such as creating users or shares or running a backup. If you're new to scripting, here are a few things to keep in mind as you get into it:

  • Adding comments to your script can help others understand what it does and helps you remember the purpose of older scripts. Use double colons (::) or a Rem statement to add comments to a script, as in the following example:
    :: Filename: myfile.bat
    rem This batch was created on 7/14/00
  • The Echo command lets you control Windows NT's default Echo functionality. By default, NT displays all commands onscreen unless you explicitly turn off the capability. Echo Off turns off all echoing, except those commands that start with Echo. @Echo Off turns off echoing for the command that follows:
    @echo off
    echo Command file processing is starting
  • Environment variables let you retrieve settings from the system's environment and substitute values when the script runs. You use the Set command to create a new environment variable. Enter the variable name between two percent symbols (%) to retrieve the contents of an environment variable, as in the following example:
    set user=tempuser
    net user %user% /add
  • Redirection lets you change the input source and output destination for your scripts. For instance, combining redirection and Echo lets you write to text files. Using one redirection symbol (>) creates a new file; using two (>>) appends text to an existing file.
    echo text line 1 > C:\temp\sample.txt
    echo text line 2 >> C:\temp\sample.txt
  • The Choice command lets you prompt users to enter a character. You can override Choice's default Y or N prompts with the /c switch. Choice sets the %errorlevel% environment variable to the ordinal number that corresponds to the user's choice.
    choice /cABC
    if %errorlevel%==1 echo You choose A
  • The If command lets you add programmatic control to a script's execution. You can use If to test the contents of an environment variable and to check whether a file exists.
    if not %os% == "Windows_NT" goto error
    if exist C:\temp\sample.txt del C:\temp\sample.txt

Contact Us | Authors | Subject Index | Directory | RSS Feeds

Copyright ©2006