String arrays and mandatory parameters

I have been working on a function to convert the output of NET SHARE commands into usable PowerShell objects. In the course of my work, I was storing the output of the command in a variable, which I later pass into a parsing function. Curiously, the function I developed iteratively in the console worked fine, but when I dressed it up in my script, it failed:

test-array : Cannot bind argument to parameter 'foo' because it is an empty string.
At line:1 char:12
+ test-array $party
+            ~~~~~~
    + CategoryInfo          : InvalidData: (:) [test-array], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,test-array

I had verified that the variable was of type System.Array, and that it had string elements. After banging my head on it for a while, I decided to break out the parameter handling and test it separately. I wrote a quick function to accept and process the elements of a string array:

function test-array {
param( [string[]] $foo )
    $i = 0
    foreach ( $line in $foo ) {
        write "[$i] $line"
        $i++
    }
}

When I created an array of strings and passed it into the function, it performed as expected:

PS Z:> $party = 'cleric','fighter','rogue','wizard'
PS Z:> test-array $party
[0] cleric
[1] fighter
[2] rogue
[3] wizard

The error message describes an inability to bind an empty string, so I added a empty string value to my array and tried again:

PS Z:> $party = 'cleric','fighter','','rogue','wizard'
PS Z:> test-array $party
[0] cleric
[1] fighter
[2] rogue
[3]
[4] wizard

So passing an array of strings to a function works fine. Then I added the mandatory parameter property to the function definition:

function test-array {
param( [parameter(Mandatory=$true)] [string[]] $foo )
    $i = 0
    foreach ( $line in $foo ) {
        write "[$i] $line"
        $i++
    }
}

Running the test with the same array elements as before elicited the error seen previously:

PS Z:> $party
cleric
fighter

rogue
wizard
PS Z:> test-array $party
test-array : Cannot bind argument to parameter 'foo' because it is an empty string.
At line:1 char:11
+ test-array <<<<  $party
    + CategoryInfo          : InvalidData: (:) [test-array], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,test-array

Since the output of the NET SHARE command includes blank lines, I’ll have to forego including the mandatory parameter property.

Leave a Reply