使用Try / Catch / Finally捕获所有Powershell错误

时间:2014-05-01 13:35:48

标签: powershell

我有一个超过1500行的Powershell脚本,该脚本已得到增强,可将进度和错误记录到Azure表存储。

问题是并非记录所有错误。

这是否是在不更改脚本和捕获所有错误的情况下实现此目的的最简单方法?

$ErrorActionPreference = "Stop"

function a
{
    "a"
}

function b
{
    "b"
    Get-Content foo
}

function c
{
    "c"
}

Try
{
    a
    b
    c
}
Catch
{
    "Catch & Log Error"
    $Error[0].Exception
}
Finally
{
    "The End"
}

更新

输出结果为:

a
b
Catch & Log Error
Cannot find path 'C:\foo' because it does not exist.
The End

1 个答案:

答案 0 :(得分:0)

您可以将它放在脚本的顶部:

$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop

...所有错误都将“表现”为终止错误并被 try...catch 块捕获。