Skip to content

/errors/cmd/was-unexpected-at-this-time

cmd: ... was unexpected at this time.

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
Command Prompt (cmd)
exit code
255
versions
Windows 10, Windows 11, Windows Server 2016+
os
windows

... was unexpected at this time. is cmd's parse error. The word before was unexpected is the token cmd did not expect at that point, after variables were expanded. Three batch-file bugs cause almost all of them: an empty variable in an if test (echo was unexpected), %i instead of %%i in a for loop (i was unexpected), and a value with ) expanded inside a block (\Microsoft was unexpected, from C:\Program Files (x86)\Microsoft). The batch file stops at that line.

Reproduce the three cases

Each case is written to its own batch file, since the error ends the batch that contains it:

cmd
> case1.cmd echo @set "ANSWER="
>> case1.cmd echo @if %%ANSWER%%==yes echo y
cmd /d /c case1.cmd 2>&1
> case2.cmd echo @for %%i in (a b) do @echo %%i
cmd /d /c case2.cmd 2>&1
> case3.cmd echo @set "P=C:\Program Files (x86)\Microsoft"
>> case3.cmd echo @if 1==1 (
>> case3.cmd echo   @echo %%P%%
>> case3.cmd echo )
cmd /d /c case3.cmd 2>&1
echo case3: ERRORLEVEL=%ERRORLEVEL%

Output

echo was unexpected at this time.

/tmp/work>@if ==yes echo y
i was unexpected at this time.

/tmp/work>@for i
\Microsoft was unexpected at this time.

/tmp/work>  @echo C:\Program Files (x86)\Microsoft
case3: ERRORLEVEL=255

Fixes

MessageBugFix
echo / goto / ==x was unexpectedempty variable in if %VAR%==xif "%VAR%"=="x"
i was unexpectedfor %i in a batch filefor %%i in (...) do
\Microsoft was unexpected (or another path part)value with ) inside ( ... ) blockecho "%P%", or setlocal enabledelayedexpansion and echo !P!
*.txt was unexpectedfor %%f in *.txtfor %%f in (*.txt) do

The fixed versions:

cmd
> fixed.cmd echo @setlocal enabledelayedexpansion
>> fixed.cmd echo @set "ANSWER="
>> fixed.cmd echo @if "%%ANSWER%%"=="yes" (echo y) else (echo answer is not yes)
>> fixed.cmd echo @for %%%%i in (a b) do @echo item %%%%i
>> fixed.cmd echo @set "P=C:\Program Files (x86)\Microsoft"
>> fixed.cmd echo @if 1==1 (
>> fixed.cmd echo   @echo !P!
>> fixed.cmd echo )
cmd /d /c fixed.cmd

Output

answer is not yes
item a
item b
C:\Program Files (x86)\Microsoft

Inside echo lines that write a batch file, %% becomes %, which is why the loop variable is written as %%%%i there; in a batch file you type %%i.

Find the failing line

Remove @echo off and run the batch from an open Command Prompt. cmd echoes each line after expansion; the last one printed before the message shows the values that broke it.

Sources