gpt4 book ai didi

powershell - 为什么代理命令对错误的处理方式不同

转载 作者:行者123 更新时间:2023-12-03 01:30:14 24 4
gpt4 key购买 nike

有一阵子,我正在维护一个PowerShell Join-Object cmdlet。
在这里,我将创建一些具有默认参数的代理命令,例如Proxy Functions: Spice Up Your PowerShell Core CmdletsFullJoin-ObjectMerge-Object,如此处所述。
(在较早的版本中,我使用别名,如果用户创建自己的别名,则可能会出现问题。)

除了主命令和代理命令之间的错误处理略有不同之外,其他所有操作均按预期进行...

根据以下函数,获取以下MVCE:

Function Inverse([Int]$Number) {
Rubbish
Write-Output (1 / $Number)
}

(如果函数 Insert-Object不存在)

比我创建一个名为 Rubbish的代理功能:
$MetaData = [System.Management.Automation.CommandMetadata](Get-Command Inverse)
$Value = [System.Management.Automation.ProxyCommand]::Create($MetaData)
$Null = New-Item -Path Function:\ -Name "Script:Inverse0" -Value $Value -Force
$PSDefaultParameterValues['Inverse0:Number'] = 0 # (Not really required for reproducing the issue)

如果我运行原始函数 Reverse0,则会收到 两个错误:
Rubbish : The term 'Rubbish' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:2 char:1
+ Rubbish
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Rubbish:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Attempted to divide by zero.
At line:3 char:1
+ Write-Output (1 / $Number)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException

如果运行代理命令 Reverse 0(或 Reverse0),我只会得到第一个错误:
Rubbish : The term 'Rubbish' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:2 char:1
+ Rubbish
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Rubbish:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException

似乎 Reverse0 0之类的内容已更改,但我检查了一下,两个函数中的内容似乎相同。

有针对不同行为的解释吗?
在错误处理方面,是否有办法使Proxy Command的行为与原始命令相同?

最佳答案

[System.Management.Automation.ProxyCommand]::Create()生成的代码当前(PowerShell Core 7.0.0-preview.5)存在缺陷:

通过在其throw块中使用$PSCmdlet.ThrowTerminatingError($_)而不是catch,它错误地将语句终止错误传播为脚本终止错误,从而导致该函数立即中止。

如果您手动更正这些调用,您的代理功能应按预期方式运行。

参见this GitHub issue;链接的问题不是专门针对此行为的,但是更改已被批准,并且应该包含针对此问题的修复程序。

具体来说,现在是,现在是,您必须手动修复生成的代码:

  • 找到所有如下所示的try/catch语句:
  •     try {
    # ...
    } catch {
    throw
    }
  • 并替换为:
  •     try {
    # ...
    } catch {
    $PSCmdlet.ThrowTerminatingError($_)
    }

    关于powershell - 为什么代理命令对错误的处理方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878604/

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