gpt4 book ai didi

powershell - 如何让 powershell 函数返回一个对象并设置 $? $假?

转载 作者:行者123 更新时间:2023-12-03 16:28:54 25 4
gpt4 key购买 nike

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

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

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

最佳答案

来自 Bruce Payettes PowerShell In Action (Second Edition) :

The $? variable will be true if the entire operation succeeded, and false otherwise. For example, if any of the operations wrote an error object, then $? will be set to false even if the error was discarded using redirection. This is an important point: it means that a script can determine whether an error occurred even if the error isn’t displayed.



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: ' + $?)

输出:
$? 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

关于powershell - 如何让 powershell 函数返回一个对象并设置 $? $假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8901507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com