PowerShell Rotate Logs

PowerShell Rotate LogsOne of the weakest point I find in Windows Operating Systems and application is the lack of proper log rotation functions/abilities and I think this is one of the oldest problems every admin have faced at some point be it with IIS, TSM or other application writing logs to the disk.

PowerShell Rotate Logs – Do I need all those files?

In my experience 99% you will never need 10 years worth of logs, ok in financial sectors this could be slightly different, so what I usually do is just getting rid of logs older than X days so to avoid them filling up the whole disk.

Probably you are wondering why I choose to delete the files rather than compress and archive in a folder, main reason for this is I don’t want to use any third-party tool like 7zip, Winzip or similar to have the job done (on the net you can find plenty of examples on how to do this) in a future post I will illustrate how to achieve this.

Second reason is that while I do know which COM object to leverage to compress files I never found the time to write proper code to handle this so I just resort to the good old “get rid of the files” method, as I said 99% you will never need those files again.

PowerShell Rotate Logs – Get the job done

Ok enough talking let’s get down to business, below you can find a quick script that I put together to cleanup log files on  multiple servers that I manage:

function sendReport()
{
	# Format email message body
	$style = "<style>BODY{font-family: Verdana; font-size: 10pt;} </style>"
	# Change variables parameters to configure script for your environment
	$smartHost = "smtp.helocheck.com"
	$sendTo = "helocheck@helocheck.com"
	$sendFrom = "LogRotate@helocheck.com"
	$mailSubject = "Log rotation for $((get-date).toshortdatestring())"
	$mailBody = "$filecount files/directories have been deleted from $rootPath in the attached log file a complete report" | ConvertTo-Html -Head $style
	Send-MailMessage -Subject $mailSubject -From $sendFrom -To $sendTo -SmtpServer $smartHost -body $mailBody -Attachments $logFile -BodyAsHtml:$true
} # End sendReport Function


# Derive Script root path - If using PowerShell 3.0 or later just use the $PSCommandPath variable 
$scriptRoot = [System.IO.Directory]::GetCurrentDirectory()

# Configure LogFile
$logFile = "$(get-date -f yyyyMMdd)-RotateLogs.log"

# Check if LogFile exists
if (!(Test-Path $scriptRoot$logFile)) { New-Item -Name $logFile -ItemType file } 

# Define how many days worth of logs to keep
$daysToDelete = 30

# Define the starting point for deleting files
$fileAging = (Get-Date).AddDays(-$daysToDelete)

# Define the path where to delete files/folders
$rootPath = "C:log_dir"

# Scan directory and get objects to be removed
$filesBuffer = Get-ChildItem -Path $rootPath -ErrorAction 'Stop' | Where-Object {$_.lastWriteTime -lt $fileAging}

# Count the total number of files/folders deleted
$fileCount = ($filesBuffer).Count

if ($filesBuffer -eq $null)

	{ 
	# Write error in the log file in case no files is older than the specified timefram
	"No files matched the search criteria" | Out-File $logFile -Append
	exit 1
	}

else {
	foreach ($tmpFile in $filesBuffer) {
	# Write everything to the log file
	"Removing $($tmpFile.fullname)." | Out-File $logFile -Append
	
	# The force switch is used to workaround the permissions related error in PowerShell
	Remove-Item $tmpFile.fullname -Recurse -Force
	}
}

sendReport

# Delete the log file once sent the email message
Remove-Item $logFile

The script will go through the directory defined as $rootPath deleting all files which are older than the number of days defined in the $dayToDelete variable, finally all filenames will be sent via email for reporting reasons via the SendReport function that I have illustrated in my previous post.

In the next post I will illustrate how it is possible to compress and archive logs rather than delete straight away so be sure to subscribe to RSS so to be notified as soon as a new post is published!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s