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.这可能吗?
来自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)
| 归档时间: |
|
| 查看次数: |
7318 次 |
| 最近记录: |