首页 > 解决方案 > 根据文件名中的日期创建批处理文件并移动文件

问题描述

我有大量文件名都以时间戳结尾的 excel 文件,如下所示:

示例文件_2018_08_24_110222.xlsx

我想根据时间戳的月份和年份移动所有这些文件,但我希望文件夹名称是上个月。因此,对于上面的示例,我想创建一个名为 July2018 的文件夹并将该文件移动到该文件夹​​中。是否可以使用批处理文件执行此操作?

标签: batch-file

解决方案


我认为这会做你需要做的事情。我添加了一些评论,所以如果您不理解代码行,请告诉我。

@ECHO OFF

REM get a list of the files
FOR %%F IN (*.xlsx) DO (
    REM GET 2nd, 3rd and 4th parts of file name: examplefile_2018_08_24_110222.xlsx
    FOR /F "tokens=2,3,4 delims=_" %%G IN ("%%~F") DO (
        REM GET previous month and/or year
        FOR /F "delims=" %%J IN ('powershell "(Get-Date %%H/%%I/%%G).AddMonths(-1).ToString('MMMMyyyy')"') DO (
            REM make the directory
            md "%%J" >nul 2>&1
            REM move the file
            move "%%~F" "%%J\"
        )
    )
)

推荐阅读