PowerShell: How to Use Try Catch and Print Only Error Message


You can use a try statement with a catch block in PowerShell for error handling.

Here is what each of these do:

A try statement “tries” to perform some operation.

A catch block specifies some action to perform if there is an error in the try statement.

To print only the error message in a catch block, you can use the following syntax:

try
{
    1/0
}
catch
{
    Write-Host $_
}

The following example shows how to use this syntax in practice.

Example: Use Try Catch and Print Only Error Message in PowerShell

Suppose that we would like to attempt to divide 1 by 0.

Suppose we type this operation in PowerShell without using a try statement:

We receive a message that says we attempted to divide by zero along with additional details.

Suppose that we would like to perform this same operation but use a try statement with a catch block that only displays the following error message if an error does occur:

  • Attempted to divide by zero.

We could use the following syntax to do so:

try
{
    1/0
}
catch
{
    Write-Host $_
}

The following screenshot shows how to use this syntax in practice:

PowerShell Try Catch print error

Since it’s not possible to divide 1 by 0, the catch block prints the following error message:

  • Attempted to divide by zero.

Note that we used $_ in the catch block because it contains the current object variable, which holds the error message at that point.

If you’d like, you can also format the error message to be displayed using a specific color.

For example, we can use the following syntax to print the error message using red font:

try
{
    1/0
}
catch
{
    Write-Host $_ -Foreground Red
}

The following screenshot shows how to use this syntax in practice:

PowerShell try catch print error in specific color

Notice that the error message is now printed in red.

Find more info about formatting text using the Write-Host cmdlet here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Try / Catch / Finally
PowerShell: How to Find All Files with Specific Extension
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply