Variables in Batch Files


Windows NT 4/Windows 2000 Syntax


Note:     The parts of this text that are displayed in magenta are valid for Windows 2000 only


Displays, sets, or removes cmd.exe environment variables.

SET [variable=[string]]

    variable   Specifies the environment-variable name.
string Specifies a series of characters to assign to the variable.

Type SET without parameters to display the current environment variables.

If Command Extensions are enabled SET changes as follows:

SET command invoked with just a variable name, no equal sign or value will display the value of all variables whose prefix matches the name given to the SET command. For example:


would display all variables that begin with the letter ‘P’

SET command will set the ERRORLEVEL to 1 if the variable name is not found in the current environment.

SET command will not allow an equal sign (=) to be part of the name of a variable.
However, SET command will allow an equal sign in the value of an environment variable in any position other than the first character.

One new switch has been added to the SET command in Windows NT 4, and another one in Windows 2000:

 SET /A expression SET /P variable=[promptString]

The /A switch specifies that the string to the right of the equal sign is a numerical expression that is evaluated. The expression evaluator is pretty simple and supports the following operations, in decreasing order of precedence:

       () - grouping
* / % - arithmetic operators
+ - - arithmetic operators
<< >> - logical shift
& - bitwise and
^ - bitwise exclusive or
¦ - bitwise or
= *= /= %= += -=
&= ^= ¦= <<= >>=
- assignment
, - expression separator

If you use any of the logical or modulus operators, you will need to enclose the expression string in quotes. Any non-numeric strings in the expression are treated as environment variable names whose values are converted to numbers before using them. If an environment variable name is specified but is not defined in the current environment, then a value of zero is used. This allows you to do arithmetic with environment variable values without having to type all those % signs to get their values. If SET /A is executed from the command line outside of a command script, then it displays the final value of the expression. The assignment operator requires an environment variable name to the left of the assignment operator. Numeric values are decimal numbers, unless prefixed by 0x for hexidecimal numbers, 0b for binary numbers and 0 for octals numbers. So 0x12 is the same as 0b10010 is the same as 022. Please note that the octal notation can be confusing: 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Environment variable substitution has been enhanced as follows:


would expand the PATH environment variable, substituting each occurrence of "str1" in the expanded result with "str2". "str2" can be the empty string to effectively delete all occurrences of "str1" from the expanded output. "str1" can begin with an asterisk, in which case it will match everything from the begining of the expanded output to the first occurrence of the remaining portion of str1.

May also specify substrings for an expansion.


would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result.
If the length is not specified, then it defaults to the remainder of the variable value.
If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.


would extract the last 10 characters of the PATH variable.


would extract all but the last 2 characters of the PATH variable.

Finally, support for delayed environment variable expansion has been added. This support is always disabled by default, but may be enabled/disabled via the /V command line switch to CMD.EXE. See CMD /?

Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed.
The following example demonstrates the problem with immediate variable expansion:

set VAR=beforeif "%VAR%" == "before" (set VAR=after;if "%VAR%" == "after" @echo If you see this, it worked)

would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement.
So the IF inside the compound statement is really comparing "before" with "after" which will never be equal.
Similarly, the following example will not work as expected:

set LIST=for %i in (*) do set LIST=%LIST% %iecho %LIST%

in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found.
Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty.
So the actual FOR loop we are executing is:

for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time.
If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

set VAR=beforeif "%VAR%" == "before" (set VAR=afterif "!VAR!" == "after" @echo If you see this, it worked)set LIST=for %i in (*) do set LIST=!LIST! %iecho %LIST%

If Command Extensions are enabled, then there are several dynamic environment variables that can be expanded but which don't show up in the list of variables displayed by SET.
These variable values are computed dynamically each time the value of the variable is expanded.
If the user explicitly defines a variable with
one of these names, then that definition will override the dynamic one described below:

     %CD%   -   expands to the current directory string.
  %DATE%   -   expands to current date using same format as DATE command.
  %TIME%   -   expands to current time using same format as TIME command.
  %RANDOM%   -   expands to a random decimal number between 0 and 32767.
  %ERRORLEVEL%   -   expands to the current ERRORLEVEL value.
  %CMDEXTVERSION%   -   expands to the current Command Processor Extensions version number.
  %CMDCMDLINE%   -   expands to the original command line that invoked the Command Processor.



Warning note:    A note on NT 4's SET /A switch from Walter Zackery in a message on alt.msdos.batch.nt:
  "The SET /A command has a long list of problems. I wouldn't use it for much more than simple arithmetic, although even then it truncates all answers to integers."


On the other hand, limited though it may seem, the SET command's math function can even be used for a complex task like calculating the date of Easter Day for any year.


Creating a Client VPN Policy

!— Access List for NAT-0

access-list NAT-0-INSIDE remark — No address translation for the VPN connections to Local LAN
access-list NAT-0-INSIDE permit ip

!— Access List for VPN Clients to Inside

access-list OUTSIDE-IN permit ip

!— Setting up DHCP Pool for Clients

ip local pool VPNPOOL1

!— No NAT from VPN to Inside

nat (inside) 0 access-list NAT-0-INSIDE

!— Authentication

aaa-server TACACS+ protocol tacacs+
aaa-server TACACS+ max-failed-attempts 3
aaa-server TACACS+ deadtime 10
aaa-server RADIUS protocol radius
aaa-server RADIUS max-failed-attempts 3
aaa-server RADIUS deadtime 10
aaa-server RADIUS (inside) host [Radius Server] [Radius Session Key] timeout 5
aaa-server LOCAL protocol local

!— Configure a transform set that defines how the traffic will be protected.

crypto ipsec transform-set ESP-3DES-MD5 esp-3des esp-md5-hmac

!— Create a dynamic crypto map and specify which
!— transform sets are allowed for this dynamic crypto map entry.

crypto dynamic-map VPNUSERSZONE 10 set transform-set ESP-3DES-MD5

!— Add the dynamic crypto map set into a static crypto map set.

crypto map VPNZONE 10 ipsec-isakmp dynamic VPNUSERSZONE

!— ???

crypto map VPNZONE client configuration address initiate
crypto map VPNZONE client configuration address respond

!— Enable the PIX to launch the Xauth application on the VPN Client.

crypto map VPNZONE client authentication LOCAL

!— Apply the crypto map to the outside interface.

crypto map VPNZONE interface outside

!— IKE Policy Configuration.

isakmp enable outside
isakmp identity address
isakmp client configuration address-pool local VPNPOOL1 outside
isakmp nat-traversal 20
isakmp policy 10 authentication pre-share
isakmp policy 10 encryption 3des
isakmp policy 10 hash md5
isakmp policy 10 group 2
isakmp policy 10 lifetime 86400

!— IPSec group configuration for VPN Client.

vpngroup VPNCLIENTS1 address-pool VPNPOOL1
vpngroup VPNCLIENTS1 dns-server
vpngroup VPNCLIENTS1 default-domain
vpngroup VPNCLIENTS1 idle-time 1800
vpngroup VPNCLIENTS1 password 1234567890

Kix Scripting Links;f=10;t=000019.htm

Miscellaneous Batch Scripting

@ In DOS version 3.3 and later, hides the echo of a batch command. Any output generated by the command is echoed. The at-sign can be prefixed to any DOS command, program name, or batch file name within a batch file.

    examples @ {Seperates sections of the batch file without diplaying the DOS prompt.}

@echo OFF {Hides the echo off report.}
%DIGIT Replaceable batch parameters which are defined by the user when the batch is executed. The parameters are separated by spaces, commas, or semicolons.

%digit {Digit: any digit from 0 to 9. %0 has the value of the batch command as it appears on the command line when the batch is executed. %1 represents the first string typed after the batch commmand. Each occurrence of %digit is replaced by the corresponding string from the batch command line.}
    examples MYBATCH DOC A:
COPY *.%1 %2
{Copies all .DOC files in the default directory to drive A:}
%VARIABLE% Replaces the DOS environment variable name with its environment value.

%variable% {Variable: a string of uppercase characers in the environment associated with a string value. Variable is created in the environment by using SET.}
    examples %PATH% {Returns the value of PATH, the current search path, which is executable.}

echo %PATH% {Displays the value of PATH, the current search path.}

%PROMPT% {Returns the value of PROMPT, the current prompt string, which is executable.}

echo %PROMPT% {Displays the value of PROMPT, the current prompt string.}

echo The current search path is: %PATH% {Displays the message including the current search path.}

set USER=John
if %USER%= =John goto LABEL
{Since the value of USER does equal “John”, the control is transferred to the label, LABEL.}
CALL Loads and executes a batch file from within a batch file as if it were a external command. When a second batch file completes, control is returned to the calling file.

call [drive:][path]filename [batch-parameters]
Before DOS version 3.3:
command /c [drive:][path]filename [batch-parameters]
CLS Clears the video display screen, setting the cursor in the upper left-hand corner.

ECHO Controls whether commands and comments within a batch file are displayed.

echo [ON|OFF|message|.]
    examples echo {Displays echo status}

echo ON {Restores normal display activity.}

echo OFF {Halts display of DOS prompt and commands.}

echo Processing… {Displays “Processing…” on the screen.}

echo %USER% {Displays the value of USER on the screen.}

echo. {Displays a single blank line on the screen.}

echo ^L > prn {Sends an ASCII control-code (form feed) to the printer. Press <Ctrl> plus <L> to type the ^L character.}

echo Y|Del *.* {Answers the DEL “Are you sure” question automatically.}
FOR Repeats the operation of a DOS command for each member of a list. Use CALL to execute a batch file as a command.

for %%argument in (list) do command {Argument: any letter from A to Z. List: a sequence of strings separated by spaces or commas. Wildcards are allowed.}
    examples for %%d in (A,C,D) do DIR %%d *.* {Displays the directories of drives A, C, and D sequentially.}

for %%f in (*.TXT *.BAT *.DOC) do TYPE %%f {Types the contents of all .TXT, .BAT, and .DOC files in the current default directory.}

for %%P in (%PATH%) do if exist %%P*.BAT COPY %%P*.BAT C:BAT {Copies all batch files which exist in any directory on the DOS command search path into the directory C:BAT.}

for %%f in (*.PAS) do call compile %%f {Compiles all .PAS files in the current default directory.}
GOTO Transfers control within a batch file to a line identified by a label. The label must be of the form “:LABEL“.

goto LABEL
IF Tests a condition and executes a command only if the condition is TRUE. But if the NOT modifier is present, the command will be executed only if the condition is FALSE.

if [not] condition command {Condition: errorlevel number; string1= =string2; or exist filename. Command: any DOS command, batch command, batch file name, or program name.}
    examples if [not] errorlevel number command {Errorlevel: an exit code returned by a program or an external command. The following DOS commands return an exit code: BACKUP, RESTORE, FORMAT, REPLACE, and XCOPY. Number: a numerical value (integer) against which the exit code is compared. The condition is TRUE if the exit code returned by the previous program is greater than or equal to number. The condition is FALSE if the exit code is less than number.}

BACKUP C:*.* A: /s
if errorlevel 3 goto TROUBLE
{If the BACKUP command exits with a code of 3 or higher, control will be transferred to the label TROUBLE.}

if errorlevel 3 if not errorlevel 4 echo ERROR #3 occurred
if errorlevel 4 if not errorlevel 5 echo ERROR #4 occurred
{Nested if statements that determine the exact error number.}

if [not] string1= =string2 command {The condition is TRUE if both strings are identical. The comparison is case sensitive. If either string is blank, a syntax error occurs.}

if (%1)= =(LTRS) CD C:WORDLTRS {If the first parameter is LTRS, the change directory to LTRS.}

if “%1″= =”” goto ERROR {If there is no parameter, then control is transferred to label ERROR.}

if not %2X= =X DIR %2*.* {If there is a second parameter, then display all the files contained in the directory %2.}

if not “%3″= =”” if not “%3″= =”b” if not “%3″= =”B” goto BADPARAM {If there is no third parameter or if it is anything other than b or B, then go to label BADPARAM.}

if [not] exist filename command {The condition is TRUE if filename can be located. The filename can include drive and path specifications. Wildcards are allowed.}

if exist D:%1nul CD %1 {Tests for the existence of directory %1 even if it contains no files, then changes to that directory if it exists.}

if not exist A:FLASH.EXE COPY C:PROJECTSFLASH.EXE A: {Copies FLASH.EXE to drive A, but only if it doesn’t exit there already.}
PAUSE Pauses the running of a batch file and displays the message “Press any key to continue …” on the screen. If the optional message is included, it will be displayed first. Use pause to optionally terminate the batch file with <Ctrl-Break> at a safe place. The optional message is not displayed when echo is OFF, so the message must be echoed on the preceding line.

pause [message]
    examples pause {Displays “Press any key to continue …”.}

pause < nul {Waits with no comment.}

pause Do you want to continue? {Displays “Do you want to continue?” with “Press any key to continue …” on the next line.}
REM Adds remarks to a batch file.

rem [remark]
    examples @rem {Hides the remark from display.}
SET Set will view the DOS environment or create, change, or delete environment values.

set [variable=[value]] {Variable: a string of characters, unbroken by spaces, which are converted to uppercase letters in the environment. Value: a string of characters, case specific, associated with variable.}
    examples set {Display the entire DOS environment.}

set USER=John {Sets the value of USER to the string, “John”.}

set USER= {Removes USER from the environment.}

set PATH=C:;C:DOS {Sets C:;C:DOS as the current search path.}

set PATH=%PATH%;C:TEST {Appends ;C:TEST to the current search path.}
SHIFT Shifts any parameter on the command line one position to the left. Use SHIFT to refer to multiple parameters by one name or to use more than ten parameters on a single command line.

    examples :LOOP
COPY %1 A:
if not (%1)==() goto LOOP
{Beginning with the first parameter, all the parameters listed on the command line are iterated and a file, the value of the parameter, is copied to A:.}

command > nul {Redirects command output to oblivion.}

command > file {Redirects command output to file.}

command >> file {Appends command output to file.}

command < file {Redirects file output to command.}

PATH {Displays “PATH=” followed by the value of PATH, the current search path.}

PATH directories {Sets directories as the current search path.}

PATH = directories {Sets directories as the current search path.}

PATH; {Disables extended command searching and confines the searching to the default directory.}

PROMPT {Resets the prompt string to its default, $n$g.}

CD {Displays the current directory and its path.}

. {Represents the default directory (If PATH=D:;C:SYS;C:. then current directory will be searched after D: and C:SYS).}

.. {Represents the parent of the default directory (C:TOOLSWPLTRS.DOC is the same as ..WPLTRS.DOC).}

%% {A literal “%”.}
Other Resources


Manipulating Registry from a Batch file

Manipulating Registry from a Batch file

REGEDIT /S addsome.REG                Adds registry settings from a file

REGEDIT /E d:pathfilename.REG "HKEY_XXXXWhatever Key"   Exports a a registry hive to file

Example of a registry import file

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionWinlogon]

Deleting a registrykey

[-HKEY_CURRENT_USERDummyTree]      Deletes the entire tree DummyTree

[HKEY_CURRENT_USERDummyTree]       Deletes ValueToBeRemoved from DummyTree


Enable SSH

On Cisco Pix

hostname host

ssh <ip> <mask> outside
ssh <ip> <mask> inside
ssh timeout 30

ca generate rsa key 1024
show ca mypubkey rsa
ca save all

On Cisco ASA

hostname host

ssh <ip> <mask> outside
ssh <ip> <mask> inside
ssh timeout 30

crypto key generate rsa modulus 1024

FSMO Roles

FSMO (Flexible Single Master Operations)

Two good reasons for investigating FSMO

a) Curiosity to know how this Single master operation works

b) To know what to do if you lose one of the 5 vital roles.

Background information

For most Active Directory operations, Windows 2003 uses the multiple master model.  The benefit is you can add a computer, or change a user’s password on any domain controller.  For example, if you have three domain controllers, you can physically create a new computer in the NTDS.dit database on any of the three.  Five minutes later, the new computer object will be replicated to the other two domain controllers.

Technically, the multiple master model uses a change notification mechanism.  Occasionally problems arise with duplicate operations, and as a result orphaned objects appear in the ‘LostAndFound’ folder.  The point of FSMO is that a few operations are deemed so critical that only one domain controller can carry out that process.  Emulating a PDC is the most famous example of such a Single Master Operation; creating a new child domain would be another example.

In FSMO, the Flexible word simply means that you can move the role to a more suitable domain controller.

The five FSMO roles are:

  1. PDC Emulator – For NT 4.0 BDC’s.  But also for synchronizing time and creating group policies.
  2. RID Master – Each object must have a globally unique number.  The RID master makes sure each domain controller issues unique numbers when you create objects like users.
  3. Infrastructure Master – Responsible for checking Universal group membership in multiple domain forests.
  4. Domain Naming Master – Ensures that each child domain has a unique name.
  5. Schema Master – Operations that involve expanding user properties e.g. Exchange 2000 adds the mailbox property to users.

Three of the FSMO roles (1-3) are held in each domain, whilst two (4-5) are unique to the entire forest.

Changing the FSMO rolesFSMO Roles

RID, PDC, Infrastructure (1. 2. and 3.)

You can plan a switch of Operation Master by using the Change button in the diagram right, taken from Active Directory Users and Computers, Right Click Domain, Properties, Operations Masters.

Domain Naming Master (4.)

To see the Domain Naming Master (4), check out Active Directory Domains and Trusts, Operations Master..

Schema Master (5.)

The Schema Master (5) is the most difficult FSMO to find.

1) Register the Schema Snap with this command: RUN regsvr32 schmmgmt.dll;

2) Run MMC, Add Remove Snap-in, Add Active Directory Schema

3) Select Active Directory Schema, Right Click, Operations Master.

If you ever run DCPROMO to demote a domain controller, watch out for a check box that says ‘This is the last domain controller in the domain’.  If that box is UNchecked the wizard will automatically move any FSMO roles to another domain controller.


If you find problems with domain controller connections timing out then:

a) Check DNS settings on the TCP/IP properties.

b) Check that all the FSMO servers are up and running.

c) Try this need command using NetDom:
    netdom query fsmo.

d) If you need a copy of netdom, check here.