使用函数进行PowerShell错误处理

PnP*_*PnP 7 powershell

这是我想的最佳实践问题.

在设计将在脚本中使用的函数时,处理函数内可能发生的错误的最佳方法是什么?

例如,假设我们有一个执行X和Y的基本功能:

Function Test-Function
{
    Try
    {
        <# Something in here that would generate an error #>
    }
    Catch
    {
        Throw
    }

    Return $someReturnResultIWantInMyScript
}
Run Code Online (Sandbox Code Playgroud)

我的脚本调用此函数:

Try
{
    $ValueIWantFromFunction = Test-Function
}
Catch
{
    <# Do something here #>
}
Run Code Online (Sandbox Code Playgroud)

如果Test-Function遇到终止错误,它将抛给调用者.将Try/Catch围绕在我的脚本函数调用将收到此错误并击中了自己的渔获物.然后我可以决定做什么.

如果我没有在函数中抛出错误,脚本将看不到终止错误,然后我$ValueIWantFromFunction可能包含$Null或无用的东西.

这是在脚本中使用函数和函数调用进行错误处理的好方法吗?有没有更好的办法?

The*_*le1 3

作为最佳实践,我喜欢使用异常来处理函数/脚本中的错误并记录它们,以便调用者知道出了什么问题。例如:

Function Remove-File
{
    [CmdletBinding()]
    [OutputType([Int])]
    Param(
        [Parameter(Mandatory)]
        [String]$Path
    )

    Try
    {
        Remove-Item -Path $Path
        Return 0
    }
    Catch
    {
        Return 1
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我正在设计自己的函数/cmdlet,我将生成一个[ErrorRecord]要抛出的自定义对象:

#Requires -Version 5
If ($ErrorCondition)
{
    $PSCmdlet.ThrowTerminatingError(
        [System.Management.Automation.ErrorRecord]::new(
            [System.Exception]::new('Error message'),
            'FullyQualifiedName',
            [System.Management.Automation.ErrorCategory]::DeviceError,
            $ErrorCausingObject
        )
    )
}
Run Code Online (Sandbox Code Playgroud)

使用此方法,我可以在文档中包含根据出错的情况抛出哪些错误,以便调用者可以根据抛出的错误利用多个捕获并处理它。

这里有一些不错的文章:
有关异常的一切
脚本专家:处理
OutputType 属性上的错误