Setlocal command

Updated: 11/12/2023 by Computer Hope
setlocal command

The setlocal command enables local environments to be changed without affecting anything else.

Availability

Setlocal is an internal command that is available in the following Microsoft operating systems.

Setlocal syntax

Begins localization of environment changes in a batch file. Environment changes made after SETLOCAL is issued are local to the batch file. ENDLOCAL must be issued to restore the previous settings. When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

SETLOCAL

If Command Extensions are enabled, SETLOCAL changes as follows:

SETLOCAL batch command now accepts optional arguments:

ENABLEEXTENSIONS /
DISABLEEXTENSIONS
Enable or disable command processor extensions. See CMD  for details.
ENABLEDELAYEDEXPANSION /
DISABLEDELAYEDEXPANSION
Enable or disable delayed environment variable expansion. See SET /? for details.

These modifications last until the matching ENDLOCAL command, regardless of their settings before the SETLOCAL command.

The SETLOCAL command sets the ERRORLEVEL value if given an argument. It is zero if one of the two valid arguments is given and one otherwise. Use this in batch scripts to determine if the extensions are available, using the following technique:

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

The example above works because on old versions of CMD.EXE, SETLOCAL does NOT set the ERRORLEVEL value. The VERIFY command with a bad argument initializes the ERRORLEVEL value to a non-zero value.

Setlocal examples

SETLOCAL

Ran in a batch file, the setlocal command would have all environment changes only affected in the batch file.

Tip

Also see Microsoft's above example shown in the syntax for other ways this command can be used.