批处理 - 将DIR的输出写入变量

时间:2017-11-23 08:14:32

标签: windows batch-file output

我必须将DIR的输出存储在变量中。

之前曾要求过这个问题。 hereherehere

它们都提供了与我现在使用的或多或少类似的答案:

%= Find the *.sln file and write its path to the file temp.temp =%
DIR /s/b *.sln > temp.temp

%= Read out the content of temp.temp again to a variable =%
SET /p texte=< temp.temp

%= Remove the temp.temp file =%
DEL temp.temp

%= Get only the filename without path =%
FOR %%A IN ("%texte%") DO (
    SET Name=%%~nxA
)

但就我而言,我确信DIR /s/b *.sln的输出总是单线。对我来说,看起来有点难看 a)将输出存储在外部文件中 b)在它上面运行FOR循环虽然我已经知道它只有一行。

有没有直接/更简单的方法呢?

1 个答案:

答案 0 :(得分:4)

for /f "delims=" %%a in ('dir /s /b *.sln') do set "name=%%a"

确实是最有效的方法(您可以直接处理命令的输出,不需要临时文件) %name%将包含文件的完整限定文件名(如果有多个文件,则包含最后一个文件)