Reputation: 16236
I would like to write a script with a parameter that has an existing set of values, but also allows the user to enter an unknown value. I am hoping that it will allow tab-completion from the known set, but not reject a value not yet in the known set.
In this case, there is a list of known servers. A new server might be added, so I want to allow the new server name to be entered. However, the ValidateSet() will reject anything it does not know.
This code does not work.
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true)]
[Validatepattern('.*')]
[ValidateSet('server1', 'server2', 'bazooka')]
[string]$dbhost
)
Write-Host $dbhost
Running this for a known host works well. Automatic tab-completion works with the known list of hosts. But, a new hostname will be rejected.
>.\qd.ps1 -dbname server2
server2
>.\qd.ps1 -dbname spock
C:\src\t\qd.ps1 : Cannot validate argument on parameter 'dbname'. The argument "spock" does not belong to the set "server1,server2,bazooka" specified by the
ValidateSet attribute. Supply an argument that is in the set and then try the command again.
Upvotes: 1
Views: 985
Reputation: 18051
You can use a ArgumentCompleter
script block for this purpose. See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters
Example:
function Test-ArgumentCompleter {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ArgumentCompleter({
$possibleValues = @('server1', 'server2', 'bazooka')
return $possibleValues | ForEach-Object { $_ }
})]
[String] $DbHost
)
}
Upvotes: 4