2

Currently, in my PowerShell scripts I am using [ValidateSet()] in my functions in order to limit the options for user input. Now I discovered the Enum as an alternative. I have read a couple of blogs about Enums vs ValidateSet, i.e. community.idera.com.

The advantages of ValidateSet() are supposed to be:

  1. Backwards compatibility
  2. Input validation
  3. ValidateSet() also provides IntelliSense

Advantages of Enums, i.e geekeefy and 4sysops:

  1. Input validation
  2. Avoid code repetition

Disadvantages of Enums:

  1. Not backwards compatible ( < PowerShell 5)

Now, I am wondering how to proceed. Should one continue using ValidateSet() as it has the same effect of user input validation, or are there other/better reasons why a PowerShell coder should prefer Enums over ValidateSet()?

Ola Ström
  • 209
  • 1
  • 2
  • 6
Alex_P
  • 151
  • 7
  • Powershell 5 was released about 5 years ago. How many Win7 users will be running the script? I don't think it matters all that much. – Greg Burghardt Jun 03 '20 at 20:57
  • @GregBurghardt, I am not putting too much weight on the backwards compatibility here but I am rather curious what a PowerShell developer should prefer between both options from a current point of view. I read the 4sysops article after I opened the question and I see the code repetition as a strong argument for Enums. – Alex_P Jun 04 '20 at 11:12
  • 1
    Basically I think you answered our own question. I've written my share of PowerShell scripts. I didn't know enums were a thing. I'm actually going to start using them now. They certainly feel more idiomatic in the .NET/Windows world. – Greg Burghardt Jun 04 '20 at 11:17
  • 1
    Enum also offers tab completion. The main advantage is that you only need to define an enum once and can then reuse it multiple times. ValidateSet would need to have its list repeated every time you want to reuse it. – Blaisem Dec 20 '21 at 18:15

0 Answers0