Powershell – Error Logging Module

This is my new blog to discuss various things that don’t fit into SPandCRM.com. I’ll be posting various things from PowerShell clips, exam study notes and pretty much anything else I feel like doing a write-up on.

We quite often use PowerShell scripts in scheduled tasks and the likes to carry out automated maintenance, backups etc as many people do. But how do you handle when things go wrong?

This small script aims to solve that by allowing logging and email notifications to be easily set up in any PowerShell script. Simply drop it in at the top and follow the instructions to enable easy logging of your scripts.

The Script


  1. Add the script below to the top of your PowerShell script.
  2. Configure the variables in the ‘Email Settings’ section
  3. If you want to record anything in the script to the log files then call –
    1. LogWrite (*value*)
<#======= Error Handler Setup ======
Drop the script into wherever it's needed and update the email that's sent.

Run the command below to generate an encrypted password, this is used by the 

(Get-Credential).Password | ConvertFrom-SecureString | Out-File "C:\scripts\Cred.txt"


<# Email Settings #>
$Username = "*username*"
$SmtpServer = "smtp.office365.com"
$port = 587

$to = "*Name* <*Email*>"
$from = "*Name* <*Email*>"
$subject = "*subject*"
$body = "*Body* (Supports HTML)"

$logFileLocation = "C:\Scripts\Logs\"
$logDaysToKeep = 365
<# End Email Settings #>

$formattedDate = Get-Date -UFormat %d-%m-%y
$logFile = $logFileLocation + $formattedDate + "-Log.log"
$currentDate = Get-Date
$removalDate = $currentDate.AddDays($logDaysToKeep * -1)

# Method for writing logs
Function LogWrite
   Param ([string]$logstring)
   $time = Get-Date
   Add-content $Logfile -value "$time - $logstring"

# Ensure logs directory exists
if (!(Test-Path -Path $logFileLocation)) {
    New-item -ItemType Directory -Force -Path $logFileLocation

# Remove logs older than specified number of days
$logs = Get-ChildItem $logFileLocation -include *.Log
foreach ($log in $logs) {
    if($log.LastWriteTime -lt $removalDate) {
        Remove-Item $log
        LogWrite "Removed Logs"

# Will email on any error
trap {
    $password = get-content C:\scripts\Cred.txt | convertto-securestring
    $credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $password

    Send-MailMessage -To $to `
                -From $from `
                -Subject $subject `
                -Body $body `
                -SmtpServer $SmtpServer -Port $port -UseSsl -BodyAsHtml `
                -Credential $credentials

    LogWrite "Failed due to error - $_ - EMAIL SENT"


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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.