How to insert the output of a command to variable in a batch file?

一世执手 提交于 2020-01-11 10:42:15

问题


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

How this can be achieved ?


回答1:


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




回答2:


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)




回答3:


@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!


来源:https://stackoverflow.com/questions/3839375/how-to-insert-the-output-of-a-command-to-variable-in-a-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!