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: ,

8 replies »

    • Eitan you must be new to PowerShell as any advanced writer would us specific logging over transcript. Transcript is for debugging or catching ALL details when you need to do that. In 13 years I have used start-transcript three times, all in college. Having a clean, non muddied, log file is ideal and much easier to create a second script that parses that log file. This basically creates a roundtable of automation.

      Like

      • I understand your rationale.

        I’d argue that sometimes there use cases where I would want the level of verbosity offered by start-transcript. For example, when I want to capture the output from other cmdlets/modules that I have no control over.

        But yeah, I can understand your reasoning as well.
        Still, it’s probably worth mentioning at the very least :).

        Like

Leave a comment

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