Batch file 在文件名中查找日期,并更改已过日期的名称

Batch file 在文件名中查找日期,并更改已过日期的名称,batch-file,Batch File,我有一个文件夹,其中包含以下格式的文件: 2018-08-20美国能源部J证书.pdf 2019-01-17史密斯T证书.pdf 我想做的是创建一个批处理文件,从文件名中提取日期并将其与当前日期进行比较,然后将文本“EXPIRED”添加到日期等于或早于当前日期的任何文件的前面。我不知道怎么做。我以前只写过一个批处理文件 谢谢你的帮助 注意 我做了一次搜索,看到了类似的问题,但我不太熟悉制作批处理文件,所以如果这是一个重复的问题,我道歉,但我在搜索中发现的内容不够具体,我无法理解。使用国际日期格式

我有一个文件夹,其中包含以下格式的文件:

2018-08-20美国能源部J证书.pdf

2019-01-17史密斯T证书.pdf

我想做的是创建一个批处理文件,从文件名中提取日期并将其与当前日期进行比较,然后将文本“EXPIRED”添加到日期等于或早于当前日期的任何文件的前面。我不知道怎么做。我以前只写过一个批处理文件

谢谢你的帮助

注意


我做了一次搜索,看到了类似的问题,但我不太熟悉制作批处理文件,所以如果这是一个重复的问题,我道歉,但我在搜索中发现的内容不够具体,我无法理解。

使用国际日期格式
yyy-MM-DD
是一个明智的决定,因为它可以通过比较日期字符串来比较日期

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Define here the folder containing the PDF file. The folder path must end
rem with a backslash. By default is used the folder path of the batch file.
set "Folder=%~dp0"

rem Get current date region independent and change format to YYYY-MM-DD.
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "FileNameDate=%%I"
set "FileNameDate=%FileNameDate:~0,4%-%FileNameDate:~4,2%-%FileNameDate:~6,2%"

rem Process all *.pdf files starting with a date in specified folder. The
rem inner FOR splits the current file name up on first space which means
rem the date string is assigned to loop variable J. This date string is
rem compared as string with the current date string character by character.
rem If a character in date string of current file has a lower code value
rem than the corresponding character in current date string, the function
rem strcmp used internally by cmd.exe for the string comparison returns a
rem negative number and the IF condition is true as the string comparison
rem result is less 0. The IF condition is also true if the two compared
rem strings are equal because of strcmp returns in this case 0 which is
rem less or equal value 0 used by command IF on comparing two strings
rem with LEQ as comparison operator.

for /F "delims=" %%I in ('dir "%Folder%????-??-??*.pdf" /A-D-H /B 2^>nul') do (
    for /F %%J in ("%%I") do if "%%J" LEQ "%FileNameDate%" ren "%Folder%%%I" "EXPIRED %%I"
)

endlocal
有关第一个For循环的解释,请阅读我的答案

注意:此批处理文件要求文件名中的日期和文件名的其余部分之间有一个空格字符,当然日期格式是
YYYY-MM-DD

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读为每个命令显示的所有帮助页面

  • dir/?
  • echo/?
  • endlocal/?
  • 获取/?
  • 如果/?
  • rem/?
  • ren/?
  • 设置/?
  • setlocal/?
  • wmic/?
  • wmic操作系统/?
  • wmic操作系统获取/?
  • wmic操作系统获取localdatetime/?

打开
cmd
并键入
echo%date
时,日期的格式是什么?如果我知道这一点,我可以帮忙。2018年8月20日(周一)发布的消息现在只看到评论,但Mofi击败了我:)我编写了一个非常类似的脚本,它执行的过程与您的相同。因为你抢先一步,所以我发帖子是毫无意义的。不过做得很好,就是这样!非常感谢。现在我只需要深入研究一下,试着自己去理解它。