0

I am trying to work with script blocks in a library function. I want to be sure I can reliably detect run time errors in the supplied script block and report these back. In the following example I create a script block that causes a run time error.

My expectation is that the catch block will capture it and print the error message. This does not happen. It dumps the error to the console in red text but control does not pass to the catch block at all.

$cmd = [ScriptBlock]::Create("Get-Content doesnotexist.txt")

$results = ''

try {
    $results = & $cmd
}
catch {
    $results += "Error: $($_.Exception.Message)"
}

"Results: $results"

Results:

PS:>

Can someone please help me to find the mistake in this example?

Matthew MacFarland
  • 2,413
  • 3
  • 26
  • 34
  • try catch only handles __terminating errors__. `$cmd = [ScriptBlock]::Create("Get-Content doesnotexist.txt -ErrorAction Stop")` – Matt Mar 28 '16 at 03:45
  • 1
    See this http://stackoverflow.com/questions/9948517/how-to-stop-a-powershell-script-on-the-first-error and this http://stackoverflow.com/questions/13820140/how-can-i-rethrow-an-exception-from-catch-block-in-powershell – Martin Maat Mar 28 '16 at 08:16
  • @MartinMaat The posts you referenced contained the information I needed. The default error action of continue is the reason that my try catch was being bypassed. If I change it to Stop it works the way I expect. – Matthew MacFarland Mar 28 '16 at 13:10
  • @Matt That is exactly the information I needed to solve this scripting problem. Please post this as the answer so I can accept. – Matthew MacFarland Mar 28 '16 at 13:12
  • If I cannot find a good duplicate (as I am sure there is one) I will add a proper answer here. The distinction here is that you are using a scriptblock obviously but the problem does not lie with that. – Matt Mar 28 '16 at 13:13

1 Answers1

0

I'm not entirely sure why you're going about it that way. You're going to want to display the error if it happens so just let that happen in the catch, then if results are not equal to null let it display the proper results.

$cmd = [ScriptBlock]::Create("Get-Content doesnotexist.txt")

$results = ''

try {
    $results = & $cmd
}
catch {
    write-error $_
}

if($results -ne $null){
    write-host "Results: $results"
}
<#else{
    #Error handling here, or have this action happen in the catch
}#>
nkasco
  • 326
  • 1
  • 2
  • 13
  • I agree there are several ways to handle the message. The problem is that this error does not invoke the catch block at all. That is the part I am stuck on. – Matthew MacFarland Mar 28 '16 at 02:12
  • Perhaps you need to put the try/catch within your scriptblock instead? I believe that will only work if it is a terminating error though, so you may just need to do something like a test-path and subsequent if statements to handle it that way. I guess it would be easier to point you in the right direction if I knew the exact use case. – nkasco Mar 28 '16 at 12:41