From: Patrick Canterino Date: Thu, 8 Mar 2018 20:24:36 +0000 (+0100) Subject: Allow to rotate log files X-Git-Url: https://git.p6c8.net/dsmonrot.git/commitdiff_plain/6b5e2ebbd8e5fa0c4c581670ede0eb6e987591ad?hp=a2f3d2a6a1f784fbed79a456e65070f12faf1626 Allow to rotate log files --- diff --git a/TODO.md b/TODO.md index b725eeb..28bbea6 100644 --- a/TODO.md +++ b/TODO.md @@ -5,7 +5,7 @@ - [x] ~~Check if the network drive already exists before connecting~~ ⇒ `New-PSDrive` throws an exception if drive is already connected - [x] Create a log file for the script - [x] Clean up the messages sent to the console or send them to the debug or error streams (e.g. `Write-Debug` or `Write-Error`) -- [ ] Rotate log files +- [x] Rotate log files - [x] Suppress output of some commands - [ ] Add some comments to the source code - [ ] Allow multiple backups for a day \ No newline at end of file diff --git a/dsmonrot.ps1 b/dsmonrot.ps1 index 95508a1..43f3fda 100644 --- a/dsmonrot.ps1 +++ b/dsmonrot.ps1 @@ -36,8 +36,9 @@ # Every month a new log file is created [String]$logDir = "C:\Users\Patrick\Desktop\DSMonRot\log" # Keep log files for this amount of months (excluding the current month), -# 0 for indefinite (currently not available) -[Int32]$keepLogs = 1 +# 0 or less for indefinite (currently not available) +# You should set this to at least the same as $keepMonths +[Int32]$keepLogs = 2 # Map network share to this drive letter, comment out if you don't want to use it [String]$smbDrive = "Z" @@ -227,6 +228,26 @@ function Rotate-Backup { } } +function Rotate-Log { + if($keepLogs -le 0) { + return + } + + $keepLogsCount = $keepLogs + + Get-ChildItem $logDir -File | Where-Object {($_.Name -ne "$currMonth.log") -and ($_.Name -match "^\d{4,}-\d{2}\.log$")} | Sort-Object -Descending | + Foreach-Object { + if($keepLogsCount -ge 0) { + $keepLogsCount-- + } + + if($keepLogsCount -eq -1) { + Write-Log "Deleting log file $($_.FullName)" -Path $logFile -Level Info + Remove-Item -Force $_.FullName + } + } +} + $dsAdditionalArgs = @("--UseVSS") $errorMessages = @() @@ -239,7 +260,6 @@ $dsCommand = "" $currMonth = Get-Date -format "yyyy-MM" $currDay = Get-Date -format "yyyy-MM-dd" - if(!(Test-Path $logDir)) { try { New-Item -ItemType directory -Path $logDir -ErrorAction Stop | Out-Null @@ -398,6 +418,8 @@ if($errorMessages.Count -eq 0) { $errorMessages += "Could not disconnect network drive $smbDrive`: $_.Exception.Message" } } + + Rotate-Log } if($emailOnError -and $errorMessages.Count -gt 0) {