setlocal, endlocal
setlocal and endlocal limit the scope of environment variables and command extension settings inside a batch file.
When you need temporary variables in a batch file, use setlocal to restore the original state at endlocal or when the batch file ends.
Basic syntax
setlocal [enableextensions | disableextensions] [enabledelayedexpansion | disabledelayedexpansion]
endlocal
setlocal is meant to be used inside batch files or scripts. Running it on its own at an
interactive command prompt usually has no useful effect.
What becomes local
Changes made after setlocal are valid only within that scope.
- Environment variables changed with
set - Whether command extensions are enabled or disabled
- Whether delayed environment variable expansion is enabled or disabled
Basic examples
The scope created by setlocal ends when endlocal runs or when the batch file ends. If you forget endlocal, it is executed implicitly at the end, so changes do not leak to the caller.
Without setlocal
@echo off
set VAR=Hello
echo %VAR%
Environment variables set without setlocal remain in the same command prompt session.
With setlocal
@echo off
set VAR=Before
setlocal
set VAR=Inside
echo Inside scope: %VAR%
endlocal
echo Outside scope: %VAR%
At endlocal, the changes made inside setlocal are discarded.
Common behavior
Echoing an undefined variable prints the echo state
@echo off
setlocal
set MESSAGE=Hello
endlocal
echo %MESSAGE%
In this example %MESSAGE% expands to an empty string, so only echo is executed.
With @echo off, the result is as follows (when echo gets no argument, it prints the current echo state).

中小企業経営者のためのRPA入門 RPA導入を成功させる方法

60分でわかる! AIエージェント 超 入門

コマンドラインの黒い画面が怖いんです。

知識・才能ゼロでもらく~に月10万円稼ぐ! よくわかるAI副業超入門
Combining with delayed expansion
To update and reference a variable inside a FOR loop or an IF (...) block, enable enabledelayedexpansion as well.
@echo off
setlocal enabledelayedexpansion
set COUNT=0
for %%F in (*.txt) do (
set /a COUNT+=1
echo Current count: !COUNT!
)
endlocal
In a block where delayed expansion is enabled, reference the variable as !COUNT! instead of
%COUNT%.
Passing a value out of the scope
Sometimes you want to use temporary variables but keep only the final result outside the scope.
Writing endlocal and set on the same line is a handy pattern for this.
@echo off
set RESULT=Before
setlocal
set RESULT=Done
endlocal & set "RESULT=%RESULT%"
echo %RESULT%
%RESULT% is expanded when the whole line is parsed, before endlocal runs, so Done is passed to the set that runs after endlocal.