2

Problem

When calling function f $array in code below (PowerShell v2), I am getting an error:

f : Cannot bind argument to parameter 'csvObject1' because it is null.

My Code

$hash1 = @{
    dependent_name = 'ADDM-Fun-3';
}
$obj1  = New-Object -TypeName PSObject -Property $hash1
$array = [System.Collections.ArrayList]@( $obj1, $null )

function f () {
    Param(
        [parameter(Position=0, Mandatory=$true)]
        [System.Collections.ArrayList]$array
    )
    "Hello"
}

f $array 

Question

Why does Powershell do this? It seams to me to be a design flaw - but maybe I am not seeing the big picture.

Comments

I believe this error is occurring because of the second line in the ArrayList is $null. I am slightly shocked by this 'finding' because:

  1. It has taken my about 4 hours to track down the issue.
  2. This seams to imply that using strong type defintions in the function is a bad idea because it causes PowerShell to check every element in the array which is an unexepected overhead.
  3. If I remove [System.Collections.ArrayList] from the function definition, the problem goes away.

2 Answers 2

3

You should use AllowNullAttribute as stated in about_Functions_Advanced_Parameters help topic

Param
(
    [Parameter(Position=0, Mandatory=$true)]
    [AllowNull()]
    [System.Collections.ArrayList]$array
) 

It is some kind of defensive programming. PS automatically unwraps arrays and hastables when pipelined. Think globally - you don't want empty server name in list of other server names when you pass bunch of them to function.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Both answers above are great. Coming from a Java and .NET background, it has taken me a while to get used to this "Automatic Unwrapping". I really don't like using the magic comma on return values. I have started passing parameters into functions and return values out out of functions using Properties on a PSObject. It is slightly more overhead - but at least I get predictable results.
3

Not sure why PowerShell generates an exception as null is a valid member for ArrayList. However, you can force your parameter validation by allowing nulls.

Like this:

[parameter(Position=0, Mandatory=$true)][AllowNull()][System.Collections.ArrayList] $array

Then there is no exception generated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.