Reputation: 27328
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()
Upvotes: 4
Views: 2634
Reputation: 174435
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
Upvotes: 6