Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate PowerShell Function Parameters allowing empty arrays?

I have a problem similar to THIS ONE

I'm passing to a function 3 arrays and I validate object type this way

function _TEST {
[CmdletBinding()]
param (
    [parameter(mandatory=$true)]
    [array]$Path,
    [parameter(mandatory=$true)]
    [array]$RW,
    [parameter(mandatory=$true)]
    [array]$RO
)
process {
    # my code
}

It works unless I pass to function array without elements, in that case it returns this error _TEST : Cannot bind argument to parameter 'Path' because it is an empty collection.

Is there a way to solve the problem similar to [AllowEmptyString()] in linked question or do I have to write custom code to test input variable?

like image 722
Naigel Avatar asked Jun 20 '13 09:06

Naigel


People also ask

How do you validate parameters in PowerShell?

To validate a parameter argument, the PowerShell runtime uses the information provided by the validation attributes to confirm the value of the parameter before the cmdlet is run. If the parameter input is not valid, the user receives an error message.

How do you pass parameters to a function in PowerShell?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

What is Property validation attribute in PowerShell?

Essentially, with validation attributes, you can attach live code to variables and have PowerShell execute this code whenever new values are assigned to your variables. This can be used for data validation, ensuring that only valid values are assigned. It can be used for a whole lot of other things, too, though.

How do I validate a string in PowerShell?

To perform a numerical validation, you would replace ValidateSet with ValidateRange. The text strings (Medium, Hot and Extra Hot, in this case), would need to be replaced by the acceptable numerical range. This line of code tells PowerShell that the acceptable values can be 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10.


1 Answers

Try this:

param (
    [parameter(mandatory=$true)]
    [AllowEmptyCollection()]
    [array]$Path
)

Link:

Parameter Validation Attributes

like image 76
Richard Avatar answered Oct 22 '22 19:10

Richard