【问题标题】:How to remove the oldest date folder via batch scripts?如何通过批处理脚本删除最旧的日期文件夹?
【发布时间】:2015-03-11 08:46:08
【问题描述】:

我有一个包含多个文件夹的目录,它们的文件名是日期:

...
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 日期是 Windows 系统日期。

【问题讨论】:

  • 数字代表什么?
  • @Marichyasana 这些是日期月-日名称-日数。生病发布产生这些数字的代码。

标签: windows batch-file


【解决方案1】:

试试这个:

@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 允许您获取当前日期而不受区域设置的影响。

希望对你有帮助!

【讨论】:

  • 我在set currentYear= 下填写了2015,在set currentMonth= 下填写了三月,但是它会删除每个新文件夹或旧文件夹?
  • 也尝试在set currentMonth=下输入03,但它仍然会删除其中的每个文件夹?
  • 通过使用 03 并实际使用超过一个月的文件夹,让它开始工作;)
  • 我可以对代码稍作调整吗,有什么办法可以自动化 set currentYear=set currentMonth= 它需要是自动的!
  • 此代码是自动的。它将使用wmic 命令自动设置currentYearcurrentMonth。它将删除早于本月的所有文件夹 :)