批处理脚本重命名所有子文件夹中的最新文件?

问题描述

@echo off
for /f %%i in ('dir /b /a-d /od /t:c "*.pdf"') do (
  set LastFileCreated=%%i
)
echo  The Last File Created is %LastFileCreated%
pause
:: ren %LastFileCreated% "decs365.pdf"
pause

我只有这个脚本,但不幸的是,它需要在每个子文件夹中复制,从而达不到目的,它甚至不会重命名文件。有什么办法可以添加指定路径“D:\Monthly Report”,让它把所有子文件夹中最近创建的文件重命名为“decs365”

解决方法

我建议您利用您的 中的 powershell.exe 来完成此任务:

@%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoProfile "Get-ChildItem -Filter '*.pdf' -File -Recurse | Sort-Object CreationTime -Descending | Select-Object -First 1 | Rename-Item -NewName 'Decs365.pdf'"

显然,如果您没有在同一个工作目录中运行命令,正如您在问题中所遇到的那样,您需要将该目录添加到上面的命令中,例如Get-ChildItem -Path 'C:\MyDirectoryPath' -Filter …