2

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

How this can be achieved ?

Misha Moroshko
  • 157,453
  • 220
  • 487
  • 722

3 Answers3

2

Batch files didn't handle this use case very well. I did find one thread that describes a technique using temporary files.

Jason R. Coombs
  • 39,015
  • 10
  • 79
  • 86
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!
Kalpesh Soni
  • 6,169
  • 2
  • 49
  • 53
1

On Windows, there's a better facility that comes pre-installed. Its called vbscript (and later there is Powershell ). Why don't you use vbscript instead.

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

The variable s now contains a list of files (equivalent to dir ). And if you want to store each filename into arrays, its also possible. (cmd.exe does not have arrays etc)

ghostdog74
  • 307,646
  • 55
  • 250
  • 337
  • Just a note to whoever does not like this approach just because of not liking the VB syntax (such as myself) - the same utility (`wscript`/`cscript`, which comes with Windows) supports JScript (the Javascript engine of IE) too. I've recently built an entire build system using JScript, and it was pretty good because I like Javascript. – Camilo Martin Sep 08 '12 at 00:43