我有一个文件夹,其中的文件格式如下:
2018-08-20美国能源部J证书.pdf
2019-01-17 Smith T证书.pdf
我想做的是创建一个批处理文件,将日期从文件名中拉出,并将其与当前日期进行比较,然后将文本“ EXPIRED”添加到日期相等的所有文件的开头当前日期之前或之前。我不知道该怎么做。我以前只写过一个批处理文件。
感谢您的帮助!
注意!
我进行了搜索,并且看到了与此类似的问题,但是我对制作批处理文件不是很熟悉,因此,如果这是重复问题,我深表歉意,但是我在搜索中发现的内容不足以针对我的情况我了解。
答案 0 :(得分:1)
使用国际日期格式YYYY-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 循环的说明,请阅读我在%date% produces different result in batch file上的答案。
注意:该批处理文件要求文件名中的日期和其余文件名之间必须有一个空格字符,当然日期格式为YYYY-MM-DD
。
要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。
dir /?
echo /?
endlocal /?
for /?
if /?
rem /?
ren /?
set /?
setlocal /?
wmic /?
wmic os /?
wmic os get /?
wmic os get localdatetime /?