/errors/cmd/was-unexpected-at-this-time
cmd: ... was unexpected at this time.
- 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:
> 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
| Message | Bug | Fix |
|---|---|---|
| echo / goto / ==x was unexpected | empty variable in if %VAR%==x | if "%VAR%"=="x" |
| i was unexpected | for %i in a batch file | for %%i in (...) do |
| \Microsoft was unexpected (or another path part) | value with ) inside ( ... ) block | echo "%P%", or setlocal enabledelayedexpansion and echo !P! |
| *.txt was unexpected | for %%f in *.txt | for %%f in (*.txt) do |
The fixed versions:
> 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.cmdOutput
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.