如何通过批处理脚本删除最旧的日期文件夹?

时间:2015-03-11 08:46:09

标签: windows batch-file

我有一个包含多个文件夹的目录,其日期为文件名:

...
03-Wed-11
03-Tue-10
03-Mon-09
...

如何编写删除最旧文件夹的批处理脚本。最好一个月大的文件夹?通过使用他们的文件名,选择最旧的文件名。

您无法保存包含:/的文件夹。这就是为什么以下脚本。我曾经制作日期文件夹():

for /F "tokens=1-4 delims=/ " %%A in ('date/t') do (
set DateDay=%%A
set DateMonth=%%B
set DateYear=%%C
)
set CurrentDate=%DateMonth%-%DateDay%-%DateYear%

如果你像这样回复当前日期:echo %CurrentDate%,它将显示如下:03-Web-11 date是Windows系统日期。

1 个答案:

答案 0 :(得分:0)

试试这个:

@echo off
SETLOCAL EnableDelayedExpansion

REM Need not to set the variable currentYear and currentMonth. It will be automatically set by wmic
set currentYear=
set currentMonth=


REM Setting the currentYear and currentMonth...
for /f "skip=1 tokens=1-2 delims= " %%a in ('wmic path Win32_LocalTime Get Month^,Year /Format:table') do (
    IF NOT "%%~b"=="" (
        set /a currentMonth=%%a
        set /a currentYear=%%b
        set currentYear=!currentYear:~-2,4!
        set currentMonth=!currentMonth:~-2,4!
    )
)

REM removing folder that are more than one year
for /D %%a IN (*) do (
    set folderName=%%a
    set folderYear=!folderName:~-2,9!

    if !currentYear! gtr !folderYear! (
        rmdir /S /Q !folderName!
        echo Deleted !folderName!
    )
)

REM removing folder that are more than one month    
for /D %%a IN (*) do (
    set folderName=%%a
    set folderMonth=!folderName:~0,-7!

    if !currentMonth! gtr !folderMonth! (
        rmdir /S /Q !folderName!
        echo Deleted !folderName!
    )
)

此代码将帮助您删除上个月的文件夹。例如,如果您在2015年3月在此文件夹上运行此代码:

...
01-Fri-15 //deleted, since it is more than one month
02-Thu-15 //deleted, since it is more than one month
03-Wed-15 //retained, since the batch program runs on March 2015
03-Wed-11 //deleted, since it is earlier than 2015
03-Tue-10 //deleted, since it is earlier than 2015
03-Mon-09 //deleted, since it is earlier than 2015
...

请注意,我使用wmic来获取当前日期而不是date \t。这是因为wmic允许您获取当前日期而不受区域设置的影响。

希望它有所帮助!