【问题标题】:Batch - Store output of dir command into variable - directory listing批处理 - 将 dir 命令的输出存储到变量中 - 目录列表
【发布时间】:2016-10-10 11:33:23
【问题描述】:

我需要将整个目录列表存储到一个变量中,然后将所述变量作为参数传递给另一个脚本。直接或首先将 dir 的输出存储到文本文件,然后执行以下操作:

dir \path\todir > temp.txt
set /p VAR=<temp.txt

但上面只读取一行。有人可以帮忙吗?

【问题讨论】:

  • 变量只有一行。
  • set /P 读取任何重定向或管道输入的第一行;要读取所有行,您需要一个for /F 循环并通过使用some syntax hack 生成换行符来单独连接每个读取行;请注意,环境变量的总长度限制为 8190 字节,包括变量名称(从 Windows 的 XP 后版本开始)。但是,问问自己是否真的有必要将所有行存储到一个变量中,或者是否有更简单、更方便的可能性......
  • 就像@achipfl 说的:其他脚本会对输出 od DIR 做什么?
  • 你应该Edit你的问题并添加其他脚本的源代码并解释更多你的最终目标!

标签: batch-file variables directory


【解决方案1】:

由于您没有向我们提供有关您的最终目标的任何其他信息;

我发布了一些内容,或许可以为您提供任何想法,以便使用类似以下代码的数组轻松存储变量:

@echo off
set "folder=%userprofile%\Desktop"
setLocal EnableDelayedExpansion
REM Populate the array with existent sub-folders in this folder
for /f "tokens=* delims= " %%a in ('Dir /b /a:d "%folder%"') do (
    set /a N+=1
    set "Folder[!N!]=%%a"
)
Rem Populate the array with existent files in this folder
for /f "tokens=* delims= " %%a in ('Dir /b /a:-d "%folder%"') do (
    set /a M+=1
    set "File[!M!]=%%a"
)
::*****************************************************************
:Display_Folders
cls & color 0E
echo Just showing only Folders :
echo(
For /L %%i in (1,1,%N%) do (
    echo Folder[%%i] = !Folder[%%i]!
)
echo(
echo Hit any key to show only files :
pause>nul
::*****************************************************************
:Display_Files
cls & color 0B
echo Just showing only Files :
echo(
For /L %%j in (1,1,%M%) do (
    echo File[%%j] = !File[%%j]!
)
echo(
echo Hit any key to exit :
Pause>nul & exit

【讨论】:

    猜你喜欢
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多