この関数を考えてみましょう:
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]
Trace-Command からの出力を解釈する経験がありません。[string]の出力に次の行が含まれていることに気付きました。
arg [string] を param [PsCustomObject] にバインド成功
PowerShell[string]が[PsCustomObject]. しかし、'string' -is [pscustomobject]評価すると$false.
これにより、次の質問が残ります。
[string]PowerShell が aと a の型の違いに基づいてパラメーター セットを選択できないのはなぜ[pscustomobject]ですか?- その理由は、PowerShell が a
[string]をa と見なすため[pscustomobject]ですか? もしそうなら、それはなぜですか? - 異なるタイプを使用して異なるパラメーター セットを選択できるようにする回避策はありますか?