batを実行した場所にあるファイル(.bat, .txt以外)の作成日時を取得し、./年/月/日/のフォルダ構成に整理するスクリプトです。自分用のメモですので、実行結果は自己責任でお願いします。
@echo off
setlocal enabledelayedexpansion
REM ログファイルの設定
set "LOGFILE=%~dp0files_log.txt"
echo Log file: %LOGFILE%
echo. > "%LOGFILE%"
REM 処理対象のフォルダを指定(現在のフォルダを使用)
set "SOURCE_FOLDER=."
echo Source folder: %SOURCE_FOLDER% >> "%LOGFILE%"
REM ファイルを処理
for %%F in ("%SOURCE_FOLDER%\*") do (
set "EXTENSION=%%~xF"
set "FILENAME=%%~nxF"
if /I not "!EXTENSION!"==".bat" if /I not "!EXTENSION!"==".txt" (
echo Processing file: "!FILENAME!" >> "%LOGFILE%"
REM ファイルの作成日時を取得
for /f "tokens=1-3 delims=/ " %%a in ("%%~tF") do (
set "YEAR=%%a"
set "MONTH=%%b"
set "DAY=%%c"
)
REM 月と日をゼロ埋め
set "MONTH=0!MONTH!"
set "MONTH=!MONTH:~-2!"
set "DAY=0!DAY!"
set "DAY=!DAY:~-2!"
echo Retrieved date: !YEAR!-!MONTH!-!DAY!
echo Retrieved date: !YEAR!-!MONTH!-!DAY! >> "%LOGFILE%"
REM 年月日が取得できた場合、ファイルを移動
if defined YEAR if defined MONTH if defined DAY (
set "DATE=!YEAR!/!MONTH!/!DAY!"
set "DEST_FOLDER=!SOURCE_FOLDER!\!DATE!"
echo Destination folder: "!DEST_FOLDER!" >> "%LOGFILE%"
if not exist "!DEST_FOLDER!" (
mkdir "!DEST_FOLDER!"
if !errorlevel! neq 0 (
echo Error creating directory: "!DEST_FOLDER!" >> "%LOGFILE%"
goto :error
)
)
move "%%F" "!DEST_FOLDER!"
if !errorlevel! neq 0 (
echo Error moving file: "!FILENAME!" to "!DEST_FOLDER!" >> "%LOGFILE%"
goto :error
) else (
echo Moved "!FILENAME!" to "!DEST_FOLDER!" >> "%LOGFILE%"
)
) else (
echo Could not determine date for "!FILENAME!" >> "%LOGFILE%"
)
echo. >> "%LOGFILE%"
)
)
echo Processing complete. >> "%LOGFILE%"
echo Check "%LOGFILE%" for detailed information.
goto :eof
:error
echo An error occurred. Check "%LOGFILE%" for details.
pause
exit /b 1
コメント