0

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

1
  • 2
    Please edit the question. Add your code and error messages as text, not as images. Pictures are hard to read, one cannot search those and copying any code requires extra effort. What's more, explain what's the desired output. Commented Sep 18, 2019 at 5:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Please edit the answer and explain why single line would work instead of using multiple lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.