Dilshad Abduwali
Dilshad Abduwali

Reputation: 1458

How to validate Parameters against a long set in PowerShell?

I am writing a script which will accept a few parameters. I need to validate one parameter that user will have to enter. I use for [ValidateSet(...)] feature of Param block. However, I need to validate this parameter against a very long hash table. Since my hash table is declared after Param, How do I validate the user inputs against the keys of that hash table?

Upvotes: 1

Views: 916

Answers (1)

mklement0
mklement0

Reputation: 438018

Ansgar Wiechers rightly points out that in your case you need to perform the argument validation inside your script, given that the values to validate against aren't yet available at script declaration (parsing) time; using a script block (for simplicity) to demonstrate the technique:

& { 
   param(
    [string] $SomeParam
   ) 

   # The hashtable to validate against.
   $hashTable = @{ foo = 1; bar = 2; baz = 3 }

   # Check the -SomeParam argument against the keys of $hashTable.
   if (-not $hashTable.ContainsKey($SomeParam)) { 
     Throw "Invalid -SomeParam argument: $SomeParam"
   }

   # ...

}  bar  # OK, because 'bar' is a key in $hashTable

Upvotes: 3

Related Questions