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.

1 Answer 1


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?

  • After a bit more testing, it appears you are correct. I tried that and then just saw it print out everything after "DO" and didn't think it worked right, but I can then run an ECHO command afterwards and it works correctly. Mar 26, 2015 at 21:24
  • This seemingly simple solution took me quite some time to find. Thank you for this.
    – user46338
    May 11, 2020 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.