4

I'm trying to assing value returned from function to a variable, but the variable is still null. Why?

function Foo{
    Param([string]$key, 
          [system.collections.generic.dictionary[string,system.collections.arraylist]] $cache)

    if (-not $cache.ContainsKey($key))
    {
        $cache[$key] = New-Object 'system.collections.arraylist'
    }
    $result = $cache[$key]
    return $result #when debugging, this is not null
}

$key = ...
$cache = ...

#EDIT: $result = Foo ($key, $cache)
#Im actually calling it without comma and bracket:
$result = Foo -key $key -cache $cache
$result.GetType()

#results in: You cannot call a method on a null-valued expression.
#At line:1 char:1
#+ $result.GetType()

1 Answer 1

6

Two things to watch out for - when you call a cmdlet or function in PowerShell, positional arguments are NOT comma-separated:

Foo($key,$cache)             # wrong, you supply a single array as the only argument
Foo -key $key -cache $cache  # correct, named parameter binding
Foo $key $cache              # correct, (implicit) positional parameter binding

Second off, PowerShell is super eager to enumerate all arrays that you pass along the pipeline, so when you do:

return New-Object System.Collections.ArrayList

PowerShell tries to output all the individual items in the arraylist, and since it's empty, nothing is returned!

You can circumvent this by wrapping the ArrayList in an array with the unary array operator (,):

return ,$result
Sign up to request clarification or add additional context in comments.

1 Comment

Great! The first point was just typo error when I wrote question, but the second, that's the tricky one...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.