PowerShell

PowerShell: How to create Logging for your PowerShell Scripts

So you have already created your first PowrShell scripts? Now you want to enhance this scripts with error logging ? If your answer is yes, jump in this this article. I will show you how to implement a custom function that captures the errors and writes errors in an error log file. Let’s get started.

Sample Code

Here is the code example you can build on. I will explain the individual blocks in more detail afterwards.

# Create Log File

$LogFile = "$home\error.log"
Clear-Content $LogFile -ErrorAction SilentlyContinue

# Create Custom Function for further operations
Function Log-Write
{
   Param ($Text)

   Add-Content $LogFile -Value $Text
}

<# 
Sample script
Search for Folders. 
If not present write them into log file and create Event Log entry.
#>

$folders = 'C:\quaxi','C:\temp','C:\'

foreach ($item in $folders) {
 Try
 {
   Get-ChildItem -Path $item -ErrorAction Stop | Out-Null
 }
 Catch
 {
  Log-Write -Text "$item is not present."
  Write-EventLog -LogName Application -Source "EventSystem" `
  -EventId 3001 -EntryType Error -Message "$item is not present."
}
}

# Check if it worked (Open Log File + Search Event Log)

Start-Process $LogFile
Get-EventLog -LogName Application -InstanceId 3001 | 
Select-Object TimeGenerated,EntryType,Message |
Format-Table -AutoSize -Wrap

Here is the explanation.

Line 1 – 4 creates a log file. It also clears content of previously generated log files.

Line 6 – 12 generates a custom function called Log-Write.

Line 14 – 33 performs a test. The foreach loop searches for folders. If they are not present, the catch block will capture them and write them into the log file using the function Log-Write. The catch block will create an Event Log entry with the ID 3001, too.

Line 37 – 40 is only for testing purposes. It will open the log file and search the eventlog log for envent id 3001.

It will look like this.

Hope you enjoyed this article. See you next time.

Categories: PowerShell

Tagged as: ,

4 replies »

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 )

Google photo

You are commenting using your Google 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.