Powershell script: send report of errors via e-mail & keep a log

# (c) Nathan Bunting (http://www.nathanbunting.com)
# Gather the "error" event types from the system log and send them over by e-mail daily.
# Delete log files older than 7 days.
#
$strLog = "system"
$strType = "error"
$filDate = get-date -uformat "20%y-%m-%d" # Get the date in a format we can use for a file
$logPath = "c:\logs\"
# Makes a log file with the date prefix (for ex. "c:\logs\2010-01-18log.txt")
$outPut = $logPath+$filDate+"log.txt"
# Check if the log file exists from before
$fileExists = Test-path $outPut
if ($fileExists -eq "True")
{
write-host "You have already taken the log for today!" -foregroundcolor "Red"
$dir = get-childitem $logPath
write-host $dir
}
else
{
# Get the event log and output to a file.  
get-Eventlog $strLog | Where-Object { $_.entryType -eq $strType } | out-file $outPut -force
# Send as an e-mail attachment
$filename = $outPut
# Use an SMTP server which can relay!
$smtpServer = “smtp.netpower.no”
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = “administrator@bergensadvokatene.com
$msg.To.Add(”nathan@netpower.no”)
$msg.Subject = “Nightly Log File”
$msg.Body = “The nightly log file is attached”
$msg.Attachments.Add($att)
$smtp.Send($msg)
# delete log files older than 7 days after sending
$Now = Get-Date
$Days = “7”
$TargetFolder = $logPath
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -recurse | Where {$_.LastWriteTime -le “$LastWrite”}
if ($files -contains "")
{
foreach ($File in $Files)
{write-host “Deleting File $File” -foregroundcolor “Red”;  Remove-Item $File | out-null}
}
else
{
write-host "Nothing to delete which is older than 7 days" -foregroundcolor "Red"
}
}
Posted on 2:21 PM by Nathan aka Mysteryn11 and filed under , | 0 Comments »

0 comments: