Setlocal enableextensions что это
Перейти к содержимому

Setlocal enableextensions что это

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

I notice in most scripts, the two are usually in the same line as so:

Are the two in fact separate commands and can be written on separate lines?

Will setting ENABLEDELAYEDEXPANSION have an adverse effect on a script if it is set on the first lines of the script and not disabled until the end of the script?

user avatar

4 Answers 4

I think you should understand what delayed expansion is. The existing answers don’t explain it (sufficiently) IMHO.

Typing SET /? explains the thing reasonably well:

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:

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:

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:

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:

Another example is this batch file:

This prints x2 and y2 : every 1 gets replaced by a 2.

Without setlocal enabledelayedexpansion , exclamation marks are just that, so it will echo !b:1=2! twice.

Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2% uses the value b has before the loop: z2 (but y2 when not set).

Команда Setlocal

Обеспечивает начало области задания для установки некоторых значений в заданном пакетном документе. Предусматривается использование локального окружения до момента, когда используется endlocal или не настанет завершение пакетного документа. Если запускать Setlocal за пределами сценария или пакетного документа, то она не станет работать.

Синтаксис

Расшифровка

enableextension

Позволяет использовать расширения командного процессора (КП). Они будут применяться до того периода, пока не возникнет endlocal. Отличительной особенностью является тот факт, что состояние расширений КП не оказывает влияния на процесс.

disableextensions

Завершает применение расширения КП до тех пор, пока не возникнет endlocal. Как и в предыдущем случае, состояния расширений КП перед setlocal не играют роли.

enabledelayedexpansion

Обеспечивает начало работы расширений переменной среды (ПС). Предусматривается задержка, пока не возникнет команда endlocal.

disabledelayedexpansion

Расширения ПС будут выключены. Имеется определенная задержка до возникновения endlocal. Это происходит без какого-либо воздействия или влияния со стороны состояния КП перед setlocal.

Используется в тех ситуациях, когда поставлена задача отобразить справочные сведения.

MS-DOS and Windows command line 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.

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 will be zero if one of the two valid arguments is given and one otherwise. You can use this in batch scripts to determine if the extensions are available, using the following technique:

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

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

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *