How to Log Error Messages to a File Using PowerShell Try Catch?

One of my team members asked me how to write errors in a log file in PowerShell. It is easy to do. In this tutorial, I will explain how to log error messages to a log file using try catch in PowerShell.

PowerShell try catch error message to log file

I will show you step by step how to use PowerShell’ try catch and finally block to log error messages in a log file.

But before that, let me help you understand the basics of try, catch, and finally blocks:

  • try block: Contains the code that might throw an error.
  • catch block: Executes if an error occurs in the try block.
  • finally block: Contains code that runs regardless of whether an error occurred or not. This block is optional.

Now, let me show you a step-by-step guide to using try, catch, and finally blocks to log errors to a file in PowerShell.

Step 1: Write the Try Block

Normally, the try block contains the code that might throw an error. So, you should place the code you want to monitor for errors in the try block. Suppose you are performing a file operation that might fail.

try {
    # Attempt to read a file that may not exist
    $content = Get-Content -Path "C:\NonExistentFile.txt"
    Write-Output "File content: $content"
}

Check out PowerShell Throw Exception with Message

Step 2: Implement the Catch Block

The catch block will handle any errors that occur in the try block. Here, we will log the error message to a text file. You can also check How to Create a Log File in PowerShell.

catch {
    # Define the log file path
    $logFile = "C:\Logs\MyLogFile.log"
    
    # Get the error message
    $errorMessage = $_.Exception.Message
    
    # Log the error message to the file
    Add-Content -Path $logFile -Value "$(Get-Date) - Error: $errorMessage"
    
    # Optionally, output the error message to the console
    Write-Output "An error occurred: $errorMessage"
}

Step 3: (Optional) Add a Finally Block

The finally block is optional and can be used to clean up resources or perform actions that should occur regardless of whether an error occurred.

finally {
    Write-Output "Script execution completed."
}

If an error occurs in the try block, it is caught in the catch block and written to a log file.

Here is the complete PowerShell script.

$ErrorActionPreference = "Stop"

try {
    # Attempt to read a file that may not exist
    $content = Get-Content -Path "C:\NonExistentFile.txt"
    Write-Output "File content: $content"
}
catch {
    # Define the log file path
    $logFile = "C:\Logs\MyLogFile.log"
    
    # Get the error message
    $errorMessage = $_.Exception.Message
    
    # Log the error message to the file
    Add-Content -Path $logFile -Value "$(Get-Date) - Error: $errorMessage"
    
    # Optionally, output the error message to the console
    Write-Output "An error occurred: $errorMessage"
}
finally {
    Write-Output "Script execution completed."
}

I executed the above PowerShell script, and you can see the exact output in the screenshot below. It logs the error message in the log file.

powershell try catch error message to log file

Note: For some reason, the catch block was not executing. To ensure that the catch block is triggered for non-terminating errors, you can set the $ErrorActionPreference variable to Stop. So, I have added $ErrorActionPreference = “Stop” at the top of the script.

In this tutorial, I explained how to log error messages to a log file using PowerShell’s try-catch and finally block.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.