batch-file - 批量递归遍历目录

标签 batch-file

情况是这样的: 我有一个包含许多带有 pdf 文件的子文件夹的文件夹。我想制作一个批处理脚本,遍历每个子文件夹,如果超过 100 个,则压缩 pdf 文件(使用 7Zip,不寻求该部分的帮助)。

这是我第一次处理 Windows 批处理脚本,我非常沮丧。我在谷歌上花了几个小时,但我认为我对这个问题没有任何了解。我找到了很多引用资料和示例代码,但没有找到大量逐字逐句的示例代码。我发现语法对用户非常不友好。

无论如何,这就是我所拥有的:

@echo off
for /r %%A in (.) do (
set pdfCount = "Code that gets the total number of pdf files in current directory, something like dir *.pdf?"
if pdfCount GEQ 100 (
set beginDate = "Code that gets the date of the oldest pdf, use in the zip file name"
set endDate = "Code that gets the date of the newest pdf, use in the zip file name" 
"Use a 7Zip command to zip the files, I am not asking for help with this code"
DEL *.pdf
echo %pdfcount% files zipped in "Code for current directory"  
)
) 
pause

我的理解是“for/r %%A in (.) do ()”应该执行每个子目录中的代码。

最佳答案

此脚本依赖于区域设置,这意味着它取决于日期和时间在您的计算机上的格式化方式。我的机器使用 mm/dd/yyyy hh:mm am 格式。该脚本将创建名称格式为 PDF yyyy_mm_dd yyyy_mm_dd.7z 的 zip 文件。

@echo off
setlocal disableDelayedExpansion
for /r /d %%P in (*) do (
  set "beg="
  set /a cnt=0
  pushd "%%P"
  for /f "eol=: delims=" %%F in ('dir /b /a-d /od *.pdf 2^>nul') do (
    set /a cnt+=1
    set "end=%%~tF"
    if not defined beg set "beg=%%~tF"
  )
  setlocal enableDelayedExpansion
  if !cnt! gtr 100 (
    for /f "tokens=1-6 delims=/ " %%A in ("!beg:~0,10! !end!") do (
      7zip a "PDF %%C_%%A_%%B %%F_%%D_%%E.7z" *.pdf
      del *.pdf
    )
  )
  endlocal
  popd
)

关于batch-file - 批量递归遍历目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010820/

相关文章:

batch-file - MSDOS 在屏幕上打印整个批处理文件而不是执行

windows - 如何使用 Windows 命令行将 12 小时格式的时间添加到文件名?

batch-file - 命令 "time 1:10" "echo %time%"返回 1 :09

batch-file - 为什么在 "set/p"提示时使用 Ctrl+C 取消 Windows 批处理脚本会产生不一致的行为?

windows - 在 Windows 中将命令的输出重定向到文件而不换行

windows - 批处理文件 - 如何启动非默认浏览器?

batch-file - 多次 ping 尝试后批处理崩溃

windows - 如何为 svn 提交和更新编写批处理文件

windows - 嵌套文件 : path and extension filter

batch-file - 允许非管理员用户使用 mklink