Windows的"dir"命令:指定"/s"时,按日期对文件进行排序 [英] Windows 'dir' command: sort files by date when '/s' is specified
问题描述
目标:我想使用批处理文件将具有特定扩展名的最新文件从源目录"复制到目标目录".最新文件可能位于源目录中的几个子目录下.
Goal: I want to copy the latest file with a certain extension from a "source directory" to a "destination directory" using a batch file. The latest file may be under several sub-directories within the source directory.
这个问题/答案正是我想要的,但是当/s
选项已指定(如
This question/answer is exactly what I want, however it does not seem to sort when the /s
option is specified (as this comment would suggest):
FOR /F "delims=|" %%I IN ('DIR "K:\path\tp\source\dir\*.ext" /B /S /O:D') DO SET NewestFile=%%I
copy "%NewestFile%" "C:\path\to\destination\dir"
您可以单独测试 DIR"K:\ path \ tp \ source \ dir \ *.ext"/B/S/O:D
来查看其是否排序.
You can test DIR "K:\path\tp\source\dir\*.ext" /B /S /O:D
by itself to see that it does not sort.
我尝试过的事情:该命令本身确实起作用: DIR"K:\ path \ tp \ source \ dir \ *.ext"/S/B |排序
,但我不知道如何在for循环中使用它(即使在文件末尾有 pause
的情况下,批处理文件也会退出,然后再确定错误).
What I've Tried: This command by itself does work: DIR "K:\path\tp\source\dir\*.ext" /S /B | sort
but I can't figure out how to use it in a for loop (batch file exits before I can determine the error - even with a pause
at the end).
有什么想法吗?
请参阅: dir文档
推荐答案
您可以根据需要从批处理文件中调出 Powershell
.在 Powershell
的较新版本中,可以缩短此代码.
You can call out to Powershell
from you batch file if you want to. This code can be shortened on newer versions of Powershell
.
for /F "delims=" %%G IN ('powershell "gci -rec | where { ! $_.PSIsContainer } | sort LastWriteTime | select -last 1 | Select-Object fullname"') do set NewestFile=%%G
完整答案:
cd /d "K:\path\to\source\dir"
for /F "delims=" %%G IN ('powershell "gci -rec *.ext | where { ! $_.PSIsContainer } | sort LastWriteTime | select -last 1 | Select-Object fullname"') do set NewestFile=%%G
copy "%NewestFile%" "C:\path\to\dest\dir"
这篇关于Windows的"dir"命令:指定"/s"时,按日期对文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!