Passing in an empty set throws an error

I'm trying to use a HashSet in my powershell script as per this answer.

Add-Type -AssemblyName System.Core
$set= new-object 'System.Collections.Generic.HashSet[string]'

But if I make a function which expects such a set

function foo([Parameter(Mandatory=$true)][Collections.Generic.HashSet[string]]$set){

and pass in the set

foo($set)

I get an error if $set is empty:

Cannot bind argument to parameter '$set' because it is an empty collection.
    + CategoryInfo          : InvalidData: (:) [script.ps1], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyCollectionNotAllowed,script.ps1

But if I add something to $set beforehand I dont get an issue.

Why cant the parameter bind to an empty set, and how can I get it to bind to such a set?

Upvotes: 2

Views: 2211

Answers (1)

MatthewG
MatthewG

Reputation: 9293

You can mark the function as allowing the empty HashTable using the AllowEmptyCollection attribute:

function foo([Parameter(Mandatory=$true)][AllowEmptyCollection()][Collections.Generic.HashSet[string]]$set)

Upvotes: 8

Related Questions