Home NT Commands
NT Syntax

SETLOCAL

Begin localisation of environment variables in a batch file.

syntax
      SETLOCAL
   
      SETLOCAL ENABLEEXTENSIONS | DISABLEEXTENSIONS

Changes made to an Environment Variable after SETLOCAL has been issued are local to the batch file.

Issuing an ENDLOCAL command will restore the previous environment variables.

For scripts that may also run on legacy Windows machines as well as Windows NT use this...

 IF (%OS%) == (Windows_NT) SETLOCAL 

 :: detail of batch script goes here

 IF (%OS%) == (Windows_NT) ENDLOCAL 

Overloading a variable

SETLOCAL can be used more than once in the same batch file so that multiple values can be stored in one Environment Variable.

For example:
@echo off
::
::Standard commission
SET V_Commission=20
echo %V_Commission%
::
::Super commission
SETLOCAL
set V_Commission=30
echo %V_Commission%
::
::Premium commission
SETLOCAL
set V_Commission=40
echo %V_Commission%
ENDLOCAL
::
::Back to Super commission
echo %V_Commission%
ENDLOCAL
::
::back to Standard commission
echo %V_Commission%

DISABLEEXTENSIONS- will attempt to disable Command extensions. (ENABLEEXTENSIONS - will attempt to re-enable)

SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of the two valid arguments
is given and one otherwise.

You can use this in a batch file to determine if command extensions are available, using the following technique:

   VERIFY errors 2>nul
   SETLOCAL ENABLEEXTENSIONS
   IF ERRORLEVEL 1 echo Unable to enable extensions

This works because "VERIFY errors" sets ERRORLEVEL to 1 and then the SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available (e.g. if the script is running under command.com)

If Command Extensions are permanently disabled then SETLOCAL ENABLEEXTENSIONS will not restore them.

Related Commands:

ENDLOCAL - End localisation of environment changes in a batch file.

Equivalent Linux BASH commands:

readonly - Mark variables/functions as readonly



Simon Sheppard
SS64.com