How to catch an exception thrown in another Powershell script?

I have 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 that sub.ps1 throws from main.ps1?

Example main.ps1:

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

Example sub.ps1:

throw new-object System.ApplicationException "I am an exception";
+3
source share
1 answer

Here is a simple example:

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

Use help about_Try_Catch_Finallyfor more information. Another way is to use trap, see help about_trap. If you have a C # or C ++ background, I would recommend using the Try_Catch_Finally method (but it also depends on what exactly you are doing).

+5
source

Source: https://habr.com/ru/post/1745253/


All Articles