Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell multiple function params from ValidateSet

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.

like image 720
SokIsKedu Avatar asked Jan 20 '17 11:01

SokIsKedu


People also ask

How do you pass multiple parameters in PowerShell?

Refer below PowerShell script for the above problem statement to pass multiple parameters to function in PowerShell. Write-Host $TempFile "file already exists!" Write-Host -f Green $TempFile "file created successfully!" Write-Host -f Green $FolderName "folder created successfully!"

What is ValidateSet in PowerShell?

The ValidateSetAttribute attribute specifies a set of possible values for a cmdlet parameter argument. This attribute can also be used by Windows PowerShell functions.

Is ValidateSet case sensitive?

By default, the ValidateSet attribute is case insensitive. This means that it will allow any string granted it's in the allowed list with any capitalization scheme.


2 Answers

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
like image 154
Mathias R. Jessen Avatar answered Sep 30 '22 12:09

Mathias R. Jessen


@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.

like image 24
Alan T Avatar answered Sep 30 '22 10:09

Alan T