Matthew MacFarland
Matthew MacFarland

Reputation: 2729

Can I use a constant in the ValidateSet attribute of a PowerShell function parameter?

I am using the ValidateSet attribute on one of my PowerShell function parameters like so:

[ValidateSet('Development','Test','Production')]
[string]$Context

I have repeated this is many places throughout a scripting project. Can these literal strings be replaced with a constant?

Upvotes: 15

Views: 4927

Answers (2)

Aileron79
Aileron79

Reputation: 897

Adding this to help others searching for a similar solution. I was looking for a way to validate parameters against the keys of a global hash table. This is what I ended up doing:

$global:MyHash = @{
    "anyitem"  = @{"name" = "somename1"; "count" = 42 };
    "someitem" = @{"name" = "another name"; "count" = 1337 };
}

function Test-Hash
{
    param
    (
        [Parameter(mandatory = $true)] [ValidateScript( { $_ -in $global:MyHash.Keys } )] [string[]] $items
    )
}

Test-Hash -items anyitem, someitem

I ended up replacing ValidateSet with ValidateScript as I realized (as mentioned in this thread as well) that the code block in ValidateSet does not work at all. Instead validating against the keys of a hash table one could easily use something like

$validParams = @('opt1', 'opt2')

and in the ValidateScript codeblock

{ $_ -in $validParams }

This is basically what I assume should answer the question.

Upvotes: 4

briantist
briantist

Reputation: 47792

No, it has to be a literal or a scriptblock. The scriptblock option seems pointless since it seems to use the literal (string) value of the scriptblock instead of executing it.

So effectively, from my testing, you must use literals.

If you use a dynamic parameter instead you could achieve this, but that's way overkill just to be DRY.

If you try to use a variable, it won't work (and ISE will give you the red squiggly). The help text erroneously says it must be a constant, but it means literal.

I created a constant with:

Set-Variable -Option Constant

And it still does not work.

Upvotes: 12

Related Questions