Question:
I’m looking for a way to make a cmdlet which receives parameter and while typing, it prompts suggestions for completion from a predefined array of options.
I was trying something like this:
1 2 3 4 5 6 7 8 9 10 |
$vf = @('Veg', 'Fruit') function Test-ArgumentCompleter { [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [ValidateSet($vf)] $Arg ) } |
The expected result should be:
When writing ‘Test-ArgumentCompleter F’, after clicking the tub button, the F autocompleted to Fruit.
Answer:
To complement the answers from @mklement0 and @Mathias, using dynamic parameters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$vf = 'Veg', 'Fruit' function Test-ArgumentCompleter { [CmdletBinding()] param () DynamicParam { $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $true $AttributeCollection.Add($ParameterAttribute) $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($vf) $AttributeCollection.Add($ValidateSetAttribute) $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter('Arg', [string], $AttributeCollection) $RuntimeParameterDictionary.Add('Arg', $RuntimeParameter) return $RuntimeParameterDictionary } } |
Depending on how you want to predefine you argument values, you might also use dynamic validateSet values:
1 2 3 4 5 6 7 8 9 10 11 12 |
Class vfValues : System.Management.Automation.IValidateSetValuesGenerator { [String[]] GetValidValues() { return 'Veg', 'Fruit' } } function Test-ArgumentCompleter { [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [ValidateSet([vfValues])]$Arg ) } |
note: The
IValidateSetValuesGenerator
class[read: interface]
was introduced in PowerShell 6.0