简体   繁体   中英

Batch - Write output of DIR to a variable

I have to store the ouput of DIR in a variable.

This was asked before eg here or here or here .

They all provide an answer more or less similar to what I'm using right now:

%= 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
)

But in my case I'm sure that the ouput of DIR /s/b *.sln will allways be a one-liner . To me it looks a bit ugly to have to
a) store the ouput in an external file and
b) run a FOR loop over it though I already know it will only have one line.

Is there any direct/simpler way to do this?

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

indeed is the most efficient method (you can process the output of a command directly, no need for a temporary file).
%name% will contain the full qualified file name of your file (or the last of the files, if there are more than one)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM