Powershell Image Conversion script – Part 2: Logging functionality

Standard

One of the important parts of the script is the logging functionality. Because we’re dealing with large amounts of files that are converted it’s good to know what has been done and may have gone wrong.

The following code will write the logfile:

# Function Write-Logfile
# This function writes, in case of an error, a rule to the logfile
# The logfile will be created with the following format: yyyymmdd
#
# Parameters:
# [string] $message: Message that need to be written
Function Write-Logfile([string]$message)
{
# set up date
$date = Get-Date -format "yyyyMMdd"
# get time for the logging
$logtime = Get-Date -Format "[HH:mm:ss]"
#set up the path to logfile
$logfile = $logdir + "\" + "logfile-" + $date + ".log"
# add the contect to the file
Add-Content $logfile "$logtime $message"
}

The function will write a line in a logfile. If no logfile exists it will create a logfile with the following name: logfile-yyyymmdd.log. An example of the name could be: logfile-20100922.log
If the file already exists it will not be created, instead it will write to the file. The log in the file would look similar to this:

09:22 Image 87623e8668762 converted

The function uses the local variable $logfile that has been added as a parameter during execution.
To add the log functionality to the “Convert-Image” do the following:

After the code:

# Create a new imageobject
$oldImage = new-object System.Drawing.Bitmap $sourceImage
[/cc]

add the following code:
[cc lang="powershell"]
# If there is an error write to logfile
If($Error.Count -ne 0)
{
Write-Logfile($Error)
$Error.Clear()
}
[/cc]

After the code:
[cc lang="powershell"]
# Save the new image
$newImage.Save($newFile, ([system.drawing.imaging.imageformat]::$imageFormat))

add the following code:

# Write the results to a logfile
Write-Logfile "Image $newFile converted"

Leave a Reply

Your email address will not be published.