Windows Command Line – Fix ‘Was Unexpected at This Time’ Error in FOR/DO Command

command linewindows

Trying to run the following directly from the command prompt.

FOR /f "delims=[] tokens=2" %%a in ('ping %computername% -4 -n 1 ^| findstr "["') do (set ip=%%a)

While it runs fine from within a batch file, if run pasted directly into a command prompt, I get the following error:

%%a was unexpected at this time.

How do I need to change it to work directly from the command prompt and NOT require a batch file?

Long story requirements:

I have a requirement of basically providing a list of commands that can be run via copy/paste into a command prompt, WITHOUT using a batch file (just go with it, not my requirements but those given to me and can't be budged). I have a later command that would echo %ip% to a .txt file.

Best Answer

When referencing For loop variable within a batch file you need to double up the percent signs (ie: %%a), but if you do this when just running the command straight at the prompt it won't work. You need to change them to a single percent sign (%a).

Perhaps check out this other SU question for more info: What does the percent sign (% and %%) in a batch file argument mean?

Related Question