1

I've just noticed that if you are using ValidateSet for a parameter variable in a function you cannot within that function change the parameter variable to a value that is not in the set.

Here is a simple example to demonstrate:

Function Test {
    [cmdletbinding()]
    Param(
        [ValidateSet(1,2,3)]
        [int]$Number
    )

    $Number = 4
}

Test 3

Returns:

The variable cannot be validated because the value 4 is not a valid value for the Number variable.

I've used Get-Member to explore $Number and I can't see any indication of how (or why) it restricts the variable like this. I assume it's some sort of custom object or strong typing but the variable looks to be a System.Int32. Does anyone know how/why this happens?

This isn't unique to Int variables, this is just a simple example. I have found the same true for a String Array parameter.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68

1 Answers1

3

I discovered from this related question: Find the values in ValidateSet that if I do the following inside my function:

(Get-Variable 'Number').Attributes.ValidValues

this lists the defined ValidateSet values. I therefore assume setting this attribute is how ValidateSet works, with the side effect being that it is then in effect throughout the life of the variable.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • If there is a PowerShell wiki somewhere, I would strongly urge you to place this information therein! – Jeff Zeitlin Aug 02 '17 at 12:54
  • 2
    FWIW, the same goes for "strong" type constraints on assignment, compare `[bool]$a = $true;(variable a).Attributes` and `$b = $true;(variable b).Attributes` – Mathias R. Jessen Aug 02 '17 at 13:03