如何使powershell函数返回一个对象并设置$?到$ false?

Jus*_*ing 4 error-handling powershell

我在PowerShell函数中有一些代码如下所示:

try {
    Invoke-SomethingThatFails
}
catch [System.Exception] {
    Write-Error $_.Exception.Message;
    return New-Object Namespace.CustomErrorType -Property @{
        'Code' = "Fail";
        "Message" = $_.Exception.Message;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在唯一的问题是我还想设置$?是$ false.这可能吗?

And*_*ndi 6

来自Bruce Payettes的PowerShell In Action(第二版):

$?如果整个操作成功,则变量为true,否则为false.例如,如果任何操作写了一个错误对象,那么$?即使使用重定向丢弃错误,也将设置为false.这一点非常重要:它表示即使未显示错误,脚本也可以确定是否发生错误.

PowerShell运行时管理值,$?并在管道中写入错误对象时设置为false.

更新以下是如何将错误对象写入管道但不终止它(管道):

function New-Error {
    [CmdletBinding()]
    param()
    $MyErrorRecord = new-object System.Management.Automation.ErrorRecord `
        "", `
        "", `
        ([System.Management.Automation.ErrorCategory]::NotSpecified), `
        ""
    $PSCmdlet.WriteError($MyErrorRecord)
}

$Error.Clear()
Write-Host ('$? before is: ' + $?)
New-Error
Write-Host ('$? after is: ' + $?)
Run Code Online (Sandbox Code Playgroud)

输出:

$? before is: True

New-Error : 
At C:\...\....ps1:14 char:10
+ New-Error <<<< 
    + CategoryInfo          : NotSpecified: (:String) [New-Error], Exception
    + FullyQualifiedErrorId : New-Error

$? after is: False
Run Code Online (Sandbox Code Playgroud)

  • 如果查看"about_Functions_Advanced_Methods"的PowerShell帮助条目的"错误方法"和"编写方法"部分(通过在PowerShell中使用"Get-Help about_Functions_Advanced_Methods"),您可以找到有关@Andy提供的技术的更多信息.他的回答.具体而言,PowerShell帮助条目链接到以下有用的MSDN文章:[PSCmdlet.WriteError Method](http://go.microsoft.com/fwlink/?LinkId=142157).我之所以提到这一点,只是因为我发现MSDN对`$ PSCmdlet.WriteError`函数的解释在阅读这个答案时很有帮助. (3认同)