From 5626201d4d788d902b61a3c8b680329b084234f6 Mon Sep 17 00:00:00 2001 From: dyoder Date: Thu, 27 May 2021 18:07:02 -0400 Subject: [PATCH] auto remove old logs --- Tools.ps1 | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Tools.ps1 b/Tools.ps1 index eb3e268..d983ddf 100644 --- a/Tools.ps1 +++ b/Tools.ps1 @@ -16,9 +16,15 @@ $RootDirectory, $ScriptsDirectory, $ToolsDirectory, $LogsDirectory | ForEach-Obj } ## Setup the log file for messages generated when this script is run -$LogFile = '{0}\ManagementScript_{1}.log' -f $LogsDirectory, (Get-Date -Format "yyyyMMddHHmmssffff") +$LogFilePrefix = "ManagementScript" +$LogFilePostfix = Get-Date -Format "yyyyMMddHHmmssffff" +$LogFile = "${LogsDirectory}\${LogFilePrefix}_${LogFilePostfix}.log" If ( !(Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null } +## Delete log files older than 30 days +$LogFileAllowedAge = (Get-Date).AddDays(-30) +Get-ChildItem -Path "${LogsDirectory}\${LogFilePrefix}_*.*" -Filter '*.log' | Where-Object {$_.LastWriteTime -lt $LogFileAllowedAge} | Remove-Item -Force -ErrorAction SilentlyContinue | Out-Null + ## Log a message to the log file Function LogMsg { param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Message)