2025/04/03(木)Windowsのスクリーンショットファイル名をリネーム

Windowsでスクリーンショットを撮ると"2024-08-26.png"のような日付で保存されますが、同日に複数枚とると
2024-08-26.png
2024-08-26 (1).png
2024-08-26 (2).png
...
という、どうしようもないファイル名になってくれます。いろいろ面倒なのでファイル更新日時をつかってファイル名をリネームするバッチファイルを作成。
完全なリネームは怖いのでファイルコピー生成して問題なさそうであれば元のファイルは手動で削除する方法とした。
@echo off
setlocal enabledelayedexpansion

set input_folder="C:\tmp\in"
set output_folder="C:\tmp\out"

if not exist "%output_folder%" mkdir "%output_folder%"

REM Check the number of files in the input folder
set file_count=0
for %%F in ("%input_folder%\*.png") do (
    set /a file_count+=1
)
if %file_count%==0 (
    echo No files found in the input folder.
    pause
    exit /b
)

echo Total number of files to process: %file_count%
echo ------------------------------
echo Starting the script...
echo ------------------------------

REM Initialize debug log file
set debug_log=debug_log.txt
echo Debug log started > "%debug_log%"

REM Process each file in the input folder
for %%F in ("%input_folder%\*.png") do (
    REM Store the current file name (full path)
    set "current_file=%%~F"
    REM echo Processing file: !current_file! >> "%debug_log%"

    REM Extract file's last modified date and time
    for /f "tokens=1-5 delims=/:- " %%A in ("%%~tF") do (
        set year=%%A
        set month=%%B
        set day=%%C
        set hour=%%D
        set minute=%%E
    )

    REM Initialize counter and filename variable
    set counter=00
    set new_filename=
    set duplicate_found=0
    set temp_counter=0

    REM Loop to check for duplicate filenames
    for /l %%I in (0,1,99) do (
        set temp_counter=00!temp_counter!
        set temp_counter=!temp_counter:~-2!
        set new_filename=!year!-!month!-!day!_!hour!!minute!!temp_counter!.png
        if exist "%output_folder%\!new_filename!" (
        	set /a temp_counter=!temp_counter!+1
        ) else (
	        REM echo !new_filename!
        )
    )

    REM Handle cases where no filename could be generated
    if "!new_filename!"=="" (
        echo Error generating filename for: !current_file! >> "%debug_log%"
        echo Error generating filename for: !current_file!
        goto next_file
    )

    REM Copy the file to the output folder
    copy "!current_file!" "%output_folder%\!new_filename!" >nul
    timeout /t 1 >nul
    if errorlevel 1 (
        echo Copy failed: "!current_file!" >> "%debug_log%"
    ) else (
        REM echo Copy successful: "!current_file!" saved as !new_filename!
        REM echo Copy successful: "!current_file!" saved as !new_filename! >> "%debug_log%"
    )

    :next_file
    REM echo File processing completed: !current_file! >> "%debug_log%"
)

REM Completion message
echo Script has completed. Check the log file: "%debug_log%"
pause
"set input_folder"と"set output_folder"は適宜変更し、"timeout /t 1 >nul"は不要であれば削除。