更正我的批处理脚本,以便文件夹中的文件可以根据年,月和日分组



问题:我有文件存储在C:Payment List。文件类型不同,它们的时间戳也不同。我想把文件夹中的文件分组,这样它们就可以根据文件创建的年份在父文件夹中。在父文件夹year中,我希望根据文件创建的月份将文件分组到名为month的子文件夹中。在子文件夹月,我想要的文件分组成天根据当天的文件被创建。下面是我的脚本

@echo off
rem Change this directory to the folder with the files
cd "C:Payment List"
rem Loop through all files in the folder
for %%f in (*) do (
rem Extract the year, month, and day from the file timestamp
set "YEAR=%%~tf:~6,4"
set "MONTH=%%~tf:~3,2"
set "DAY=%%~tf:~0,2"

rem Create the necessary subfolders
if not exist "%YEAR%" md "%YEAR%"
if not exist "%YEAR%%MONTH%" md "%YEAR%%MONTH%"
if not exist "%YEAR%%MONTH%%DAY%" md "%YEAR%%MONTH%%DAY%"

rem Move the file to the subfolder
move "%%f" "%YEAR%%MONTH%%DAY%"
)
pause

不幸的是,当我运行这个脚本时,我得到错误:

The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
The specified path is invalid.
0 file(s) moved.

请帮我编写脚本。

我希望脚本根据创建时间戳对文件夹中的所有文件进行分组。即从2019年5月1日起的文件必须在文件夹201951中找到。

不能在像%f这样的参数样式变量上使用替换语法。首先使用SET将值存储到一个正常变量中。

setlocal EnableDelayedExpansion
for %%f in (*) do (
rem Extract the year, month, and day from the file timestamp
set STAMP=%%~tf
set YEAR=!STAMP:~6,4!
set MONTH=!STAMP:~3,2!
set DAY=!STAMP:~0,2!
rem Create folder and subfolder if not exists
md !YEAR!!MONTH!!DAY! 2>nul
rem Move the file to the subfolder
move "%%f" !YEAR!!MONTH!!DAY!
)

你还必须激活延迟扩张。否则,将在进入循环之前设置变量。

也许你还想通过使用*.csv而不是*来防止你创建的任何文件夹显示在文件列表中,比如。

编辑:包括@Magoo的建议。

最新更新