PowerShell: single point where I can catch all exceptions
I have several PowerShell script files. a.ps1
'calls' (via dot operator) b.ps1
and c.ps1
scripts.
a.ps1 #main
b.ps1 #helper1 <- need catch error there
c.ps1 #helper2 <- error is being raised there
Is it possible inside b.ps1
file to catch terminating error that was thrown in c.ps1
file?
Thanks.
EDIT
Inside a.ps1
:
. .\b.ps1
. .\c.ps1
Inside b.ps1
:
trap {
Write开发者_开发百科-Host "my trap block"
}
Inside c.ps1
:
throw "test"
"my trap block" isn't called in this example
You can install a trap
handler in b.ps1
to handle errors in c.ps1
if you dot source b.ps1
so that it is running in the same scope as a.ps1
e.g.:
. .\b.ps1
Update: Indeed that doesn't work. It seems that PowerShell isn't honoring the notion of running in a.ps1's scope by dot sourcing. Not sure that you will be able to do anything better than this:
a.ps1 contents:
---------------
. .\b.ps1
trap {
TrapHandler $_
continue
}
.\c.ps1
b.ps1 contents:
---------------
function TrapHandler($error)
{
Write-Host "oops - $error"
}
It looks like the trap handler needs to be in a.ps1 but you can define a trap handling function in b.ps1. Still, don't think you can control the disposition (break or continue) of the error in this function.
That's really weird. Apparently trap doesn't care about scope, exactly.
I don't have a proper solution, but I have an icky workaround:
You could write this in a:
.([scriptblock]::create(( (gc .\b.ps1 -del `0) + "`n" + (gc .\c.ps1 -del `0) )))
Or the same thing, put another way:
.( [scriptblock]::create(( @(gc .\b.ps1) + @(gc .\c.ps1) -join "`n" )) )
精彩评论