问题
I've read in various places that I can use Windows batch file for to grab the output of a command and put it in a variable, like this:
FOR /F %%G IN ('foo-command') DO SET FOO=%%G
Great. So my foo-command is actually C:\Program Files\Foo\foo.bat, and this is stored in the FOO_BAT variable. And it takes a parameter bar with value blah blah='foobar' blah. So I try that:
FOR /F %%G IN ('%FOO_BAT% -bar "blah blah='foobar' blah"') DO SET FOO=%%G
I get a lovely 'C:\Program' is not recognized.... Nothing I can do can get around the space in the command.
If you want to reproduce this, create a simple C:\Program Files\Foo\foo.bat file containing just the following, and then run the line above in a batch file.
echo FooBar
How can I capture the output of a command (which takes parameters) as a Windows batch variable, if the command has spaces in its path?
- Yes, I've tried putting quotes around
%FOO_EXE%. - Yes, I've tried putting everything in a separate variable and using that single variable in the
FOR. - Please try this with the parameters I supplied before telling me it works. The presence of the parameters changes everything.
回答1:
FOR /F "delims=" %%G IN ('CALL "C:\path with spaces\foo.bat" "blah blah='foobar' blah"') do set foo=%%G
Give this a try. And yes I tested it. Foo.bat does nothing more then just echo %1.
回答2:
Whenever you are trying to process output directly from a FOR loop, I would recommend including the usebackq parameter. This allows you to include quotes in your command (as is often needed) to specify full file paths or individual parameters which have spaces in them.
For example:
REM Using the DIR command with FOR switches, extract the short name.
REM The path specified below can be fed by a variable.
FOR /F "usebackq tokens=*" %%G IN (`DIR "C:\Program Files\Foo\foo-command.exe" /B /S`) DO SET FooPathShortName=%%~sG
ECHO Short Name is: %FooPathShortName%
REM No quotes are needed to run the short name.
FOR /F "usebackq" %%G IN (`%FooPathShortName% -bar "blah blah='foobar' blah"`) DO SET Foo=%%G
In the above, I am using the DIR command to output the full path of the target executable into a format which the FOR function can parse as a file. From this I am determining the short name of the file which does not require spaces to execute in the second FOR command.
来源:https://stackoverflow.com/questions/33370883/retrieve-command-output-to-variable-when-command-has-spaces