# logrotate.ps1 # - renames and archives log files # v1.15.1228 - (c) by ibi c/o flatbyte.com # # parameters are read from logrotate.csv in the same directory # # logrotate.csv looks like this: ## ServiceToStop,ServiceToStart,PathFileMask,RenameLog,ArchiveDir,DaysToKeep ## W3SVC,W3SVC,d:\logs\php-error.log,1,d:\logs\archive,3 ## ,,v:\logs\rsFOZZIE*.log,0,d:\logs\archive,7 # # ServiceToStop: # which service should be stopped before processing log files? short name of service used by cmd.exe's "net stop" # ServiceToStart: # which service should be started after processing log files? short name of service used by cmd.exe's "net start" # --- NOTE: service names for starting/stopping are independent, but script needs admin-rights to do so. # PathFileMask: # which file names are to be processed? wild card like "*" or "?" are ok. # RenameLog: # bool for renaming files: 1- rename, 0- don't rename. # --- CAUTION: if files are not moved and wild cards are used subsequent runs will rename them again! # ArchiveDir # path where archived files are moved. NOTE: path *must* exist. # DaysToKeep # number of days, older files will be processed/moved, i.e. "7"=archive files older than 7 days Start-Transcript -path $env:temp\logrotate_$env:computername-$env:username.txt # adjust transcript-path at your will Trap { write "hoppla! - $_"; continue } # trap should be enough, you can change script to try/catch/finally if you desire. :) ipcsv .\logrotate.csv | % { # read csv file write "processing"$_.PathFileMask # dump the filemask we're processing # stop service (needs admin-rights) if (($_.ServiceToStop.trim()).length -gt 0) { spsv $_.ServiceToStop -force } # rename if param is set. adjust time format if you wish (uses .net time format) if ($_.RenameLog -eq 1) { gci $_.PathFileMask | % { ren $_.fullname $($_.basename+(get-date -f 'yyyyMMddHHmm')+($_.extension)) }} # archive if given date is less than last write time of file if ($_.DaysToKeep -ne 0) { $CompareDate = (get-date).adddays(-$_.DaysToKeep); # minus sign means date in the past (e.g. -7 days) $ArchiveDir = $_.ArchiveDir; # save pipeline object for further use, b/c gci will overwrite it gci $_.PathFileMask | where { $_.LastWriteTime -lt $CompareDate } | mv -destination $ArchiveDir -force } # start service (needs admin-rights) if (($_.ServiceToStart.trim()).length -gt 0) { sasv $_.ServiceToStart } } Stop-Transcript