Home > Back-end >  Windows command line - error when trying to run 2 command in the same line
Windows command line - error when trying to run 2 command in the same line

Time:06-20

I have a .bat file that works properly:

set list=1 5 10 18 22 27
for %%p in (%list%) do @ping 192.168.0.%%p -w 10 -n 1 | findstr "Reply Request"

When I try to run it inline, combined with & or && in one line like this

set list=1 5 10 18 22 27 && for %%p in (%list%) do @ping 192.168.0.%%p -w 10 -n 1 | findstr "Reply Request"

I get an error saying:

%%p was unexpected at this time.

What am I doing wrong?

If the combined command is in the bat file it does work, but not if pasted in the command line.

The purpose of this is to have excel generate one line copy-paste command to be run in the command prompt, as creation the batch file is not allowed on the remote system.

SOLVED: Thank you Magoo and Stephan! The solution is to enclose array:

set "list=1 5 10 18 22 27" 

And to use %p instead if %%p:

for %p in (%list%) do @ping 192.168.0.%p -w 10 -n 1 | findstr "Reply Request"

So final result:

set "list=1 5 10 18 22 27" && for %p in (%list%) do @ping 192.168.0.%p -w 10 -n 1 | findstr "Reply Request"

does work :)

PS: Magoo suggested more streamlined solution:

for %p in (1 5 10 18 22 27) do @ping 192.168.0.%p -w 10 -n 1 | findstr "Reply Request"

Simple, single command :)

CodePudding user response:

The value of list is undefined when the line is parsed, so batch substitutes nothing (the "contents" of list) for %list% and the resolved result that is executed is

set list=1 5 10 18 22 27 && for %%p in () do @ping 192.168.0.%%p -w 10...

So, what's wrong with

for %p in (1 5 10 18 22 27) do @ping 192.168.0.%p -w 10...

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal backslash, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier.

CodePudding user response:

To use a variable defined in the same line (or code block), you need delayed expansion

Delayed expansion is disabled by default, so you need to start a new instance of cmd with delayed expansion enabled:

cmd /v:on /c "set "list=1 5 10 18 22 27" & for %p in (!list!) do @ping 192.168.0.%p -w 10 -n 1 | findstr "Reply Request""

(Although I'd prefer Magoo's solution)

  • Related