Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an exception thrown in another Powershell script?

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";
like image 691
David Andreoletti Avatar asked Sep 03 '25 03:09

David Andreoletti


1 Answers

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).

like image 86
Roman Kuzmin Avatar answered Sep 07 '25 07:09

Roman Kuzmin