ashwani gupta
ashwani gupta

Reputation: 150

Unable to handle error Powershell try with catch?

Hi, I write some PowerShell cmd to get the attribute of TransportRule. I know that this('TA') particular Transport rule does not exist in the exchange, I handle that thing through try with a catch but I do not get a correct result.

$temp="error"
Try{
Get-TransportRule -Identity TA|fl
}
Catch{
$temp
}

enter image description here

Upvotes: 0

Views: 126

Answers (2)

Ivan Mirchev
Ivan Mirchev

Reputation: 839

The issue is that Try / Catch statement works only with terminating errors. You may try:

$temp="error"
Try{ 
    Get-TransportRule -Identity TA -ErrorAction Stop | Format-List 
} 
Catch{ 
    $temp
}

Another option would be to change it generally for the current session, setting the default variable $ErrorActionPreference = 'Stop'. Then you do not need to use the -ErrorAction parameter.

Hope it helps.

Upvotes: 1

Suhas Parameshwara
Suhas Parameshwara

Reputation: 1454

In the PowerShell window you should give it in a singe line like,

$temp="error"; Try{ Get-TransportRule -Identity TA|fl } Catch{ $temp }

The other way of doing this is, save it in a file with .ps1 extension and if you try to run that from powershell it will handle the exception.

enter image description here

If you use multiple lines, the command will be executed in the order and each line will be considered as a separate command. So in your image, it is executing line by line and when it comes to Get-TransportRule command it doesn't have any connection between try and catch because it's a separate command.

Hope it helps! Cheers

Upvotes: 0

Related Questions