批处理 - 将命令输出存储到变量(多行)

Batch - Store command output to a variable (multiple lines)

我知道一种有点像作弊的方法,但下面的代码会创建一个临时文件,然后将其删除。我不希望发生这种情况。那么有没有合适或更好的方法呢?

command 2>> "temp"
set /p OUTPUT=<"temp"
del "temp"
echo %OUTPUT%

我知道有一个使用 for 循环的解决方案,但它不适用于 return 超过一行结果的命令。我想将它们全部存储到我的变量中。 (我试过这个 code 顺便说一句)

长得有点丑:

for /f "delims=" %%i in ('dir notexistent.xxx  2^>^&1 1^>nul ') do echo %%i

深入讲解here

您可以将其放入包含换行符的单个变量中。

setlocal EnableDelayedExpansion
set LF=^


REM The two empty lines are required here
set "output="
for /F "delims=" %%f in ('dir /b') do (
    if defined output set "output=!output!!LF!"
    set "output=!output!%%f"
)
echo !output!

但稍后处理数据可能会有点棘手,因为嵌入了换行符。
而且每个变量仍然有 8191 个字符的限制。

通常使用数组更容易。

setlocal EnableDelayedExpansion
set "output_cnt=0"
for /F "delims=" %%f in ('dir /b') do (
    set /a output_cnt+=1
    set "output[!output_cnt!]=%%f"
)
for /L %%n in (1 1 !output_cnt!) DO echo !output[%%n]!