I have a problem with dynamic parameters:
function get-foo {
[cmdletBinding()]
param(
[parameter(Mandatory=$true)]
$Name
)
DynamicParam {
if($Name -like 'c*') {
$Attributes = New-Object 'Management.Automation.ParameterAttribute'
$Attributes.ParameterSetName = '__AllParameterSets'
$Attributes.Mandatory = $false
$AttributesCollection = New-Object 'Collections.ObjectModel.Collection[Attribute]'
$AttributesCollection.Add($Attributes)
$Dynamic = New-Object -TypeName 'Management.Automation.RuntimeDefinedParameter' -ArgumentList @('pattern','system.object',$AttributeCollection)
$ParamDictionary = New-Object 'Management.Automation.RuntimeDefinedParameterDictionary'
$ParamDictionary.Add("pattern", $Dynamic)
$ParamDictionary
}
}
end {
if($test) {
return $Name -replace '\b\w',$test
}
$name
}
}
It's detecting my pattern parameter but it returns an error;
ps c:\> get-foo -Name cruze -pattern 123
get-foo : Le paramètre « pattern » ne peut pas être spécifié dans le jeu de paramètres « __AllParameterSets
».
Au niveau de ligne : 1 Caractère : 8
+ get-foo <<<< -Name cruze -pattern u
+ CategoryInfo : InvalidArgument: (:) [get-foo], ParameterBindingException
+ FullyQualifiedErrorId : ParameterNotInParameterSet,get-foo
How to fix the problem?
Replace $AttributeCollection with $AttributesCollection ('s' is missing).
Use Set-StrictMode in order to catch such typos :)
As for the script, I think there are other issues, too. Here is the corrected and working version:
function get-foo {
[cmdletBinding()]
param(
[parameter(Mandatory=$true)]
$Name
)
DynamicParam {
if ($Name -like 'c*') {
$Attributes = New-Object 'Management.Automation.ParameterAttribute'
$Attributes.ParameterSetName = '__AllParameterSets'
$Attributes.Mandatory = $false
$AttributesCollection = New-Object 'Collections.ObjectModel.Collection[Attribute]'
$AttributesCollection.Add($Attributes)
$Pattern = New-Object -TypeName 'Management.Automation.RuntimeDefinedParameter' -ArgumentList @('pattern', [string], $AttributesCollection)
$ParamDictionary = New-Object 'Management.Automation.RuntimeDefinedParameterDictionary'
$ParamDictionary.Add("pattern", $Pattern)
$ParamDictionary
}
}
end {
if ($Name -like 'c*') {
if ($Pattern.IsSet) {
return $Name -replace '\b\w', $Pattern.Value
}
}
$name
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With