如何捕获另一个Powershell脚本中抛出的异常?

Dav*_*tti 3 exception powershell-2.0

我有两个Powershell脚本; main.ps1和sub.ps1.main.ps1调用sub.ps1.有时sub.ps1会抛出异常.是否有可能捕获sub.ps1从main.ps1抛出的异常?

示例main.ps1:

try{. .\sub.ps1;}
catch
{}
finally
{}
Run Code Online (Sandbox Code Playgroud)

sub.ps1示例:

throw new-object System.ApplicationException "I am an exception";
Run Code Online (Sandbox Code Playgroud)

Rom*_*min 5

这是一个简单的例子:

try {
    sub.ps1
}
catch {
    Write-Warning "Caught: $_"
}
finally {
    Write-Host "Done"
}
Run Code Online (Sandbox Code Playgroud)

用于help about_Try_Catch_Finally了解更多详情.还有另一种方法是使用trap,参见help about_trap.如果你有一些C#或C++背景,那么我建议使用Try_Catch_Finally方法(但这也取决于你究竟做了什么).