How to insert command output into a variable in a batch file?

Inside a batch file on Windows, I would like some kind of variable to have the output of a command dir /b.

How can this be achieved?

+2
source share
3 answers

Batch files did not do very well with this use case. I found one thread that describes a technique using temporary files .

+2
source

In Windows there is a better tool that is installed in advance. It is called vbscript (and later Powershell). Why don't you use vbscript.

strFolder="c:\test"
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFolder = objFS.GetFolder(strFolder)
s=""
For Each strFile In objFolder.Files
    s=s & strFile & vbCrLf
Next
WScript.Echo s

s ( dir). , . (cmd.exe ..)

+1
@ECHO OFF
setlocal enabledelayedexpansion
set LF=^


rem ** The two empty lines are NECESSARY
set output=
FOR /F %%i in ('dir /b') do SET output=!output!!LF!%%i
ECHO !output!
+1
source

All Articles