Capture output command CMD

女生的网名这么多〃 提交于 2019-12-27 12:07:08

问题


Platform Windows XP

When writing a command file (.bat) how can i "catch" the output from a command into a variable ?

I want to do something like this

SET CR='dir /tw /-c b.bat | findstr /B "[0-9]"'

But this do not work

Regards Stefan

PS No, I can not dowload grep, cygwin or any other software, it have to be the CMD DS


回答1:


You can use FOR /F and go through some loops inside a batch file to capture the output:

@echo off
setlocal enabledelayedexpansion
set var=
for /f "tokens=* delims=" %%i in ('dir /tw /-c b.bat ^| findstr /B "[0-9]"') do set var=!var!^

%%i

echo %var%

It is especially important that there are two newlines between !var!^ and the %%i below.

Additionally you need to escape (again using ^) all characters inside the command line for FOR that have special meaning to the shell, such as the pipe in this instance.

The solution works by iterating over the output of the command and appending each line to the contents of var incrementally. To do that in a somewhat convenient manner the script enables delayed variable expansion (the !var! syntax).




回答2:


You can use for /f for that:

for /f %%L in ('dir /tw /-c b.bat ^| findstr /b "[0-9]"') do set CR=%%L

This assumes that there is only a single line of output, though. You cannot (trivially or usefully) capture more than one line in a variable.

I can only guess what you're really trying to do here, though. If you need the file size (just guessing because of the /-c) then it's certainly easier to use

for %%X in (b.bat) do set size=%%~zX



回答3:


Youc an set an errorlevel which you exit with, and you can ask the exitcode of a command in your batch file. im not sure this is what you mean but i hope it helps.



来源:https://stackoverflow.com/questions/14646575/capture-output-command-cmd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!