Windows IIS ログローテーション


@ECHO OFF
::#############################################################
::# #
::# <スクリプト名> iis-log-rotate.bat #
::# <機能概要> IISログの圧縮ローテーション #
::# 7日より以前のファイルを圧縮 #
::# 180日後圧縮ファイルの削除 #
::# <引数> 5 #
::# ※引数なしは起動しない(誤動作防止) #
::# <入出力ファイル> なし #
::# <注記> なし   #
::#-----------------------------------------------------------#
::# #
::#############################################################

::引数チェック バッチファイルに引数をつけて実行ダブルクリックでの実行防止
if not "%1"=="5" ( exit /b )
setlocal enabledelayedexpansion
SET LPAS=C:\inetpub\logs\LogFiles\W3SVC1
::#圧縮対象ファイルの確認なければ終了
forfiles /P %LPAS% /M *.log /D -7 > nul 2>&1
if not %ERRORLEVEL% EQU 0 (exit /b)
::#ログファイルの圧縮 7日より以前のログファイル
for /f %%i in ('forfiles /P %LPAS% /M *.log /D -7') do (
SET Z=%%i
SET X=!Z:~-11,6!
powershell Compress-Archive -Path %LPAS%*!X!.log -DestinationPath %LPAS%\IIS_20!X!.zip -ErrorAction Stop > nul 2>&1
powershell Start-Sleep -s 1
powershell Remove-Item %LPAS%*!X!.log -ErrorAction Stop > nul 2>&1
)
::#180日より以前の圧縮ログファイルを削除
forfiles /P %LPAS% /M *.zip /C "cmd /c if @isdir==FALSE del /s @path" /D -180 > nul 2>&1
exit /b