gpt4 book ai didi

powershell - 为什么不能基于 [string] vs [hashtable] vs [pscustomobject] 解析参数集?

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

考虑这个函数:

function Test-Discrimination
{
[CmdletBinding()]
param
(
[parameter(ValueFromPipeline = $true,
Mandatory = $true,
ParameterSetName = 'string')]
[string]
$String,

[parameter(ValueFromPipeline = $true,
Mandatory = $true,
ParameterSetName = 'hashtable')]
[hashtable]
$Hashtable,

[parameter(ValueFromPipeline = $true,
Mandatory = $true,
ParameterSetName = 'pscustomobject')]
[pscustomobject]
$PsCustomObject
)
process
{
$PSCmdlet.ParameterSetName
}
}

管道 [pscustomobject]行为如我所料:
PS C:\> New-Object pscustomobject | Test-Discrimination
pscustomobject

但是,管道 [string]抛出异常:
PS C:\> 'string' | Test-Discrimination
Test-Discrimination : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:12
+ 'string' | Test-Discrimination
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (string:String) [Test-Discrimination], Paramete
rBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Test-Discrimination
[hashtable] 也是如此:
PS C:\> @{} | Test-Discrimination
Test-Discrimination : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:7
+ @{} | Test-Discrimination
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (System.Collections.Hashtable:Hashtable) [Test-
Discrimination], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Test-Discrimination

添加 DefaultParameterSetName='hastable'原因 [hashtable]但不是 [string]正确解决。

我没有口译经验 the output from Trace-Command .我确实注意到 [string] 的输出包括这一行:

BIND arg [string] to param [PsCustomObject] SUCCESSFUL



这似乎是 PowerShell 正在考虑 [string]成为 [PsCustomObject] .但是 'string' -is [pscustomobject]计算结果为 $false .

这一切都给我留下了以下问题:
  • 为什么 PowerShell 不能根据 [string] 之间的类型差异选择参数集和 [pscustomobject] ?
  • 原因是 PowerShell 认为 [string]成为 [pscustomobject] ?如果是这样,为什么会这样?
  • 是否有一种解决方法可以让我使用不同的类型来选择不同的参数集?
  • 最佳答案

    我相信这样做的原因是任何东西都可以转换为 [PSObject] ([PSCustomObject])。 PowerShell 尝试将值合并到目标类型。这就是为什么当您有一个参数为 [int] 时的原因。 ,可以通过"5"它会起作用,或者为什么当你有一个参数是 [ipaddress] , 你可以给它一个字符串 "1.2.3.4" .

    因此,在参数绑定(bind)期间,当您传递 [string] 时会发生什么?或 [hashtable]是它成功绑定(bind)到[pscustomboject]参数,以及(至少)其他参数之一,因此它无法解析集合。

    我不相信有任何方法可以关闭这种行为或使其“更严格”。

    顺便说一句,任何东西都可以转换为 [PSObject] 的原因是因为在 PowerShell 中,每个对象都是一个 [PSObject]已经!这也是您可以将成员添加到任何对象的任何实例的原因。 PowerShell 使这一切变得非常透明,这就是为什么正如您所说,它在这种情况下(以及其他一些情况)违反了最小意外原则。

    如果您从 C# 中与 PowerShell 交互,那么所有内容都包含在 [PSObject] 中。变得更加明显(并且在许多情况下令人讨厌),这就是我第一次意识到情况就是这样。

    关于powershell - 为什么不能基于 [string] vs [hashtable] vs [pscustomobject] 解析参数集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39902244/

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