我找不到正在解决的这个特定问题,所以我会在这里问:我似乎无法将 dynamc 参数设为位置 0 参数。当我尝试时,似乎在位置 1 定义的第一个静态参数将提升或继承位置 0,然后在下一个可用位置(位置 1)添加为位置 0 定义的动态参数:
$x=[string]::Empty;
Function foo {
[cmdletbinding()]
Param (
[Parameter(ParameterSetName="set1",
Position=1,
ValueFromPipeline=$true)]
$InputObject,
[Parameter()]
[switch]
$RequireFilePath
)
DynamicParam {
$mand = $script:x -eq $null -or `
$script:x -eq [string]::Empty -or `
$RequireFilePath.IsPresent;
$attrs = New-Object System.Management.Automation.ParameterAttribute;
$attrs.ParameterSetName = "set1";
$attrs.Mandatory = $mand;
$attrs.Position = 0;
$attrCollection = New-Object `
System.Collections.ObjectModel.Collection[System.Attribute];
$attrCollection.Add($attrs);
$FilePath = New-Object System.Management.Automation.RuntimeDefinedParameter `
"FilePath", string, $attrCollection;
$paramDictionary = New-Object `
System.Management.Automation.RuntimeDefinedParameterDictionary;
$paramDictionary.Add("FilePath", $FilePath);
$paramDictionary;
}
Begin {
if ( $FilePath.Value -eq $null -or $FilePath.Value -eq [string]::Empty) {
$FilePath.Value = $script:x;
} else {
$script:x = $FilePath.Value;
}
Write-Output ("(foo) FilePath: {0}" -f $FilePath.Value);
Write-Output ("(foo) RequireFilePath: {0}" -f $RequireFilePath.IsPresent);
Write-Output ("(foo) script:x: {0}" -f $script:x);
}
Process {
Write-Output ("(foo) InputObject: {0}" -f $InputObject);
}
End {
}
}
foo "filename2.txt" "zxcv";
执行时,我得到这个:
(foo) FilePath: zxcv
(foo) RequireFilePath: False
(foo) script:x: zxcv
(foo) InputObject: filename2.txt
我想我的期望是动态参数将是位置 0,而静态参数将是位置 1。有人可以权衡一下吗?是否可以将动态参数定义为低于(早于)静态参数的位置?