Enum parameter for powershell cmdlet


I’m writing a cmdlet (script) on powershell and I wanted to use eunm as one of the parameters. But I don’t know where to put enum definition so that it would be visible for cmdlet parameters declaration.

For example, I have a parameters definition of the script like this

and an enum like this

I can’t replace [string] with [LevelEnum] in the parameter definition because script will fail to locate enum definition. And I can’t put definition before cmdletbinding, it’s not allowed.
I know how to do it if that would’ve been a function, I know it can be solved using ValidateSet, but I need to have integer values correstonding to enum options.

But the question is, can I do the same for a cmdlet?

Thanks to everyone.
I ended up with a combination of defferent answers.


If this script needs to accept a custom enum, it means that you will be calling it from some other place, where enum definition already exists. And now you’re trying to add the same definition again in a script. It would be good idea to push it out to a module as per @Alex_P suggestion so the definition resides in one place, but the downside is that Import-Module or #Requires won’t import it, thus the need for using module clause.

But if you’re willing to accept simpler and less secure solution, you could take advantage of the fact that any enum you define is derived from System.Enum. [System.Enum]$Level will accept only and all enums and if it’s not LevelEnum the script will break, but still it filters most possible mistakes before the script execution and gives some information about parameter type.


Enum parameter for powershell cmdlet by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply