4

I have a two Powershell scripts; main.ps1 and sub.ps1. main.ps1 calls sub.ps1. Sometimes sub.ps1 throws an exception. Is it possible to catch the exception thrown by sub.ps1 from main.ps1 ?

Example main.ps1:

try{. .\sub.ps1;}
catch
{}
finally
{}

Example sub.ps1:

throw new-object System.ApplicationException "I am an exception";

1 Answer 1

6

Here is a simple example:

try {
    sub.ps1
}
catch {
    Write-Warning "Caught: $_"
}
finally {
    Write-Host "Done"
}

Use help about_Try_Catch_Finally for more details. Yet another way is to use trap, see help about_trap. If you have some C# or C++ background then I would recommend to use Try_Catch_Finally approach (but it also depends on what exactly you do).

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

6 Comments

Thanks for the answer but it has not solved the problem. I use dot sourcing to call the script. Could it be the problem ?
It works for me with dot sourcing or not. The problem is elsewhere then, more information might help. What errors exactly do you get?
Are you sure that sub.ps1 throws an exception and not just writes an error? Try this $ErrorActionPreference = 'stop' before call of sub.ps1
I found the problem. In my catch statement, there was nothing written to the output to indicate the exception was catched. Your solution definitely works. Thanks.
Still works for me with your exception.. What error do you get when you run main.ps1? Or what exactly happens? Nothing at all? Can you take a look at your $Error list?
|

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.