daily pastebin goal
78%
SHARE
TWEET

logrotate.ps1

ibi Dec 29th, 2015 (edited) 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # logrotate.ps1
  2. # - renames and archives log files
  3. # v1.15.1228 - (c) by ibi c/o flatbyte.com
  4. #
  5. # parameters are read from logrotate.csv in the same directory
  6. #
  7. # logrotate.csv looks like this:
  8. ## ServiceToStop,ServiceToStart,PathFileMask,RenameLog,ArchiveDir,DaysToKeep
  9. ## W3SVC,W3SVC,d:\logs\php-error.log,1,d:\logs\archive,3
  10. ## ,,v:\logs\rsFOZZIE*.log,0,d:\logs\archive,7
  11. #
  12. # ServiceToStop:
  13. # which service should be stopped before processing log files? short name of service used by cmd.exe's "net stop"
  14. # ServiceToStart:
  15. # which service should be started after processing log files? short name of service used by cmd.exe's "net start"
  16. # --- NOTE: service names for starting/stopping are independent, but script needs admin-rights to do so.
  17. # PathFileMask:
  18. # which file names are to be processed? wild card like "*" or "?" are ok.
  19. # RenameLog:
  20. # bool for renaming files: 1- rename, 0- don't rename.
  21. # --- CAUTION: if files are not moved and wild cards are used subsequent runs will rename them again!
  22. # ArchiveDir
  23. # path where archived files are moved. NOTE: path *must* exist.
  24. # DaysToKeep
  25. # number of days, older files will be processed/moved, i.e. "7"=archive files older than 7 days
  26.  
  27. Start-Transcript -path $env:temp\logrotate_$env:computername-$env:username.txt # adjust transcript-path at your will
  28. Trap { write "hoppla! - $_"; continue } # trap should be enough, you can change script to try/catch/finally if you desire. :)
  29.  
  30. ipcsv .\logrotate.csv | % { # read csv file
  31.     write "processing"$_.PathFileMask # dump the filemask we're processing
  32.     # stop service (needs admin-rights)
  33.     if (($_.ServiceToStop.trim()).length -gt 0) { spsv $_.ServiceToStop -force }
  34.     # rename if param is set. adjust time format if you wish (uses .net time format)
  35.     if ($_.RenameLog -eq 1) { gci $_.PathFileMask | % { ren $_.fullname $($_.basename+(get-date -f 'yyyyMMddHHmm')+($_.extension)) }}
  36.     # archive if given date is less than last write time of file
  37.     if ($_.DaysToKeep -ne 0) {
  38.         $CompareDate = (get-date).adddays(-$_.DaysToKeep); # minus sign means date in the past (e.g. -7 days)
  39.         $ArchiveDir = $_.ArchiveDir; # save pipeline object for further use, b/c gci will overwrite it
  40.         gci $_.PathFileMask | where { $_.LastWriteTime -lt $CompareDate } | mv -destination $ArchiveDir -force
  41.     }
  42.     # start service (needs admin-rights)
  43.     if (($_.ServiceToStart.trim()).length -gt 0) { sasv $_.ServiceToStart }
  44. }
  45. Stop-Transcript
RAW Paste Data
Top