为什么代理命令以不同的方式处理错误

问题描述 投票:1回答:1

有一阵子,我正在维护PowerShellJoin-Objectcmdlet。在这里,我将创建一些具有默认参数的代理命令,如FullJoin-ObjectMerge-ObjectInsert-Object,如下所述:Proxy Functions: Spice Up Your PowerShell Core Cmdlets((在早期版本中,我使用的是别名,如果用户创建自己的别名,则可能会出现问题。)>>

一切正常,但在主命令和代理命令之间的错误处理略有不同...

基于以下功能,获取了以下MVCE

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

([Rubbish函数不存在的地方]

比起创建名为Reverse0的代理功能:

$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)

如果我运行原始函数Reverse 0,则会出现two

错误:
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

如果运行代理命令Reverse0(或Reverse0 0),我只会得到第一个错误:

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

似乎$ErrorActionPreference之类的东西已经更改,但是我检查了一下,并且在两个函数中看起来都一样。

是否有针对不同行为的说明?就错误处理而言,是否有办法使Proxy命令的行为与原始命令相同?

有一阵子,我正在维护一个PowerShell Join-Object cmdlet。在这里,我使用默认参数创建了一些代理命令,如FullJoin-Object,Merge-Object和Insert-Object,如此处所述:...

powershell error-handling command
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.