批处理文件以计算子目录中的文件类型

Mr *_*est 3 windows batch-file

我需要一个批处理文件来计算子目录中的某些文件类型。在这种情况下,它是 .txt 和 .xls 文件。在文件的末尾,它会报告这一点。

@echo off
REM get script directory
set scriptdir=%~dp0
REM change directory to script directory
cd /d %scriptdir%
setlocal
set txtcount=0
set xlscount=0
for %%x in ('dir *.txt /s ) do set /a txtcount+=1
for %%x in ('dir *.xls /s ) do set /a xlscount+=1
echo %txtcount% text files
echo %xlscount% .xls files
endlocal
pause
Run Code Online (Sandbox Code Playgroud)

我的批处理文件没有报告正确的文件数。我认为它可能会不断计数,但我已将计数变量设置为本地,所以我不确定发生了什么。

zb2*_*226 5

您的脚本存在三个问题:

  • 你想遍历命令输出,所以你需要 FOR /F
  • 您没有使用“裸”/B格式,即DIR输出的不仅仅是文件名
  • 你错过了两次结束单引号

用这个替换你的循环:

FOR /F %%X IN ('DIR /S /B *.txt') DO SET /A "txtcount+=1"
FOR /F %%X IN ('DIR /S /B *.xls') DO SET /A "xlscount+=1"
Run Code Online (Sandbox Code Playgroud)