Skip to content

Instantly share code, notes, and snippets.

@danishi
Created March 19, 2022 14:50
Show Gist options
  • Save danishi/7dad6f0da2deae946d974ac270a82887 to your computer and use it in GitHub Desktop.
Save danishi/7dad6f0da2deae946d974ac270a82887 to your computer and use it in GitHub Desktop.
Log rotation in a batch file
@echo off
cd %~dp0
setlocal enabledelayedexpansion
:: Number of days to leave a log (Example: -30 = Updated 30 days ago)
set /a deleteLimit=-30
call :getTimeStamp
:: Log rotation
for /f "delims=? eol=#" %%i in (logrotate.ini) do (
if exist "%%i" (
move "%%i" "%%i_%TimeStamp%"
type nul > "%%i"
)
rem Remove Log
call :getDirName "%%i"
forfiles /P !dirname! /D %deleteLimit% /M "*.log*" /c "cmd /c del @path"
)
endlocal
exit /b
:: ***** SUBROUTINE *****
:getTimeStamp
setlocal
::YYYY/MM/DD
::0123456789
set YYYY=%DATE:~0,-6%
set MM=%DATE:~5,-3%
set DD=%DATE:~-2%
::hh:mm:ss.mm
::01234567890
set /a H=%TIME:~0,-9%
set M=%TIME:~3,-6%
set S=%TIME:~6,-3%
if %H% lss 10 (
set H=0%H%
)
endlocal & set TimeStamp=%YYYY%%MM%%DD%-%H%%M%%S%
exit /b
:getDirName
setlocal
endlocal & set dirname=%~dp1
exit /b
@danishi
Copy link
Author

danishi commented Mar 19, 2022

You can enumerate the files of interest by creating a logrotate.ini file.

# Comment
C:\Users\foo\logs\foo.log
C:\Users\bar\app\logs\bar.log

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment