function foo
{
param(
[parameter(Mandatory=$true)]
[ValidateSet('Test1','Test2','Test3')]
[String]$ChooseOne= 'Test1',
)
do xxxxxxxxxxxxxxxx
{
foo -ChooseOne Test9
I'm working on a powershell function with a set of required parameters. The validate set works great, however as Validate Set is.. if an option is entered that is not one of the listed options.. I'll get an error like below:
foo: Cannot validate argument on parameter 'ChooseOne'. The argument "Test9" does not belong to the set "Test1,Test2,Test3" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the
command again.
At line:1 char:1
+ foo
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [foo], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,foo
Is there a way to have an error action to set the wronged variable to it's default that was previously defined?
So in this case it would default $ChooseOne
to "Test1
"
In your question you explicitly pass an invalid argument to your validation set-constrained
-ChooseOne
parameter, and then ask:The answer is: no, and for a good reason: if you define your parameter to only accept an argument from a defined set of acceptable values, you expressly want to prevent passing an unacceptable value, so you want PowerShell to report an error.
If you want to accept invalid values but quietly ignore them - which seems like a bad idea - do not use a validation attribute on the parameter and instead handle the validation - and quiet reversion to a default value - in your function body.
As an aside: There is no point in defining a default value for a parameter that is marked as mandatory.
In your own answer you're changing the premise of your question to not passing any value to your
-ChooseOne
parameter.Making a parameter not mandatory, i.e., optional - which is the default, so no explicit
[parameter(Mandatory=$false)]
is needed - indeed makes any default value declared for it take effect if no argument is passed.