0
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"

  • 1
    There are plenty of advanced function examples that use parameters and their various options. Example: http://stackoverflow.com/questions/39154887/set-a-default-value-for-variable-in-powershell and also [reference TechNet](https://social.technet.microsoft.com/wiki/contents/articles/15994.powershell-advanced-function-parameter-attributes.aspx) – user4317867 Feb 19 '17 at 20:59

2 Answers2

0

In your question you explicitly pass an invalid argument to your validation set-constrained -ChooseOne parameter, and then ask:

Is there a way to have an error action to set the wronged variable to its default that was previously defined?

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Note: I believe this answer to be correct and - hopefully - helpful. If you disagree, please tell us _why_, and I'm happy to improve it. – mklement0 Sep 28 '21 at 22:21
-1

If I make the value not mandatory, it'll be able to use its default as wanted.

[parameter(Mandatory=$false)]
4c74356b41
  • 69,186
  • 6
  • 100
  • 141