5

I'm writing a script with PowerShell and at some point I needed to use ValidateSet on function params. It's a very good feature, but what I need is something more than that.

For example

Function JustAnExample
{
    param(
        [Parameter(Mandatory=$false)][ValidateSet("IPAddress","Timezone","Cluster")]
        [String]$Fields
    )

    write-host $Fields
}

So this code snippet allows me to choose one item from the list like that
JustAnExample -Fields IPAddress

and then prints it to the screen. I wonder if there is a possibility to allow to choose multiple values and pass them to function from one Validation set like so

JustAnExample -Fields IPAddress Cluster

Maybe there is a library for that or maybe I just missed something but I really can't find a solution for this.

SokIsKedu
  • 196
  • 1
  • 2
  • 17

2 Answers2

10

If you want to pass multiple string arguments to the -Fields parameter, change it to an array type ([String[]]):

param(
    [Parameter(Mandatory=$false)]
    [ValidateSet("IPAddress","Timezone","Cluster")]
    [String[]]$Fields
)

And separate the arguments with , instead of space:

JustAnExample -Fields IPAddress,Cluster
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • I have one more question. Is there a way to make those selections unique? because when I run the program I am able to choose 2 or more the same values. So what I want is to make the user be able only to choose one value from the given list. I was reading https://social.technet.microsoft.com/wiki/contents/articles/15994.powershell-advanced-function-parameter-attributes.aspx#ValidateSet but couldn't really find anything regards to this issue – SokIsKedu Jan 24 '17 at 09:50
1

@SokIsKedu, I had the same issue and could not find an answer. So I use the following inside the function:

function Test-Function {
    param (
        [ValidateSet('ValueA', 'ValueB')]
        [string[]] $TestParam
    )

    $duplicate = $TestParam | Group-Object | Where-Object -Property Count -gt 1
    if ($null -ne $duplicate) {
        throw "TestParam : The following values are duplicated: $($duplicate.Name -join ', ')"
    }

    ...
}

It does not prevent duplicates being passed in, but it does catch them.

Alan T
  • 3,294
  • 6
  • 27
  • 27