将日期变量添加到在文件夹中查找最新文件的 bat 文件

Add date variable to bat file that finds newest file within folders

我找到了一个脚本,它可以将最新的文件从一个目录复制到另一个目录并将其重命名为静态名称,这个可以。

我正在修改它以适应每天创建的文件夹中的文件。

所以文件夹结构是:

C:\Logs\Check170806
C:\Logs\Check170807 etc

脚本如下:

@echo off
set source="C:\test case"
set target="C:\Users\sam.green\Desktop\Random Folder\output.txt"

FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

有没有办法让脚本在今天的文件夹中查找并获取最新的文件并将其复制到静态位置和文件名?

我认为添加这个(但没有时间)可能会有所帮助,但不确定如何将其添加到脚本中:

set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%

我在想这样的事情会奏效:

@echo off 
set source="C:\test case\%todaysdate%\ 
set target="C:\Users\sam.green\Desktop\Random Folder\output.txt" 
set todaysdate="%yyyy%%mm%%dd%" 

FOR /F "delims=" %%I IN ('DIR %source%%todaysdates%\*.* /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END 
:END 
TIMEOUT 4

更新,所以我试过了,但它仍在复制 "test case" 文件夹中的最新文件:

@echo off
set todaysdate="%yyyy%%mm%%dd%"
set source="C:\test case\%todaysdate%"
set target="C:\Users\sam.green\Desktop\Random Folder\output.txt"

FOR /F "delims=" %%I IN ('DIR %source%\%todaysdate%*.* /A:-D /O:-D /B') DO COPY %source%\%todaysdate%"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

在意识到变量和代码主体中都指定了 %todaysdate% 之后,我也试过这个:

@echo off
set todaysdate="%yyyy%%mm%%dd%"
set source="C:\test case\"
set target="C:\Users\sam.green\Desktop\Random Folder\output.txt"

FOR /F "delims=" %%I IN ('DIR %source%\%todaysdate%*.* /A:-D /O:-D /B') DO COPY %source%\%todaysdate%"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

最新版本代码:

@echo off
for /f %%a in ('powershell -NoP -C "get-date -f "yyyyMMdd"') Do Set today=%%A
set "source=C:\test case\%today%"
set "target=C:\Users\sam.green\Desktop\Random Folder\output.txt"
Pushd "%source%"
FOR /F "delims=" %%I IN ('DIR "*.*" /A:-D /O:-D /B') DO COPY "%%I" "%target%" & echo %%I & GOTO :EOF
Popd
TIMEOUT 10
@echo off
for /f %%A in ('powershell -NoP -C "get-date -f \"yyyyMMdd\""') Do Set today=%%A

set "source=C:\test case\%today%"
set "target=C:\Users\sam.green\Desktop\Random Folder\output.txt"

Pushd "%source%" || (Echo Dir %source% not found&goto :END)

FOR /F "delims=" %%I IN ('DIR /B/A-D/O-D * 2^>Nul') DO (
    COPY /Y "%%I" "%target%" >Nul && echo copied %%~fI to %target%
    GOTO :END
)
:END
Popd
TIMEOUT 10

编辑 在我的本地 ramdisk 上进行了测试 - 现在应该可以工作了。