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?