PowerShell函数调用返回字典而非预期值的问题咨询
Ah, I see the issue here—you're tripping over a key difference between PowerShell function syntax and C-style languages you might be used to! Let's break this down step by step.
The root cause: Incorrect parameter passing
When you call foo('a',$dict), you're using syntax that works in languages like C# or Python, but PowerShell interprets this completely differently:
- In PowerShell, function parameters are separated by spaces, not commas inside parentheses.
- The expression
('a',$dict)inside parentheses is treated as a single array (@('a', $dict)) that gets passed to the first parameter$itemof your function. The second parameter$dict_of_itemends up being$nullbecause you didn't pass a value for it.
Why you see the entire dictionary
Let's walk through your function logic with this incorrect parameter passing:
$dict_of_itemis$null, so$dict_of_item.keysreturns$null.- The condition
$null -contains $item(where$itemis the array@('a', $dict)) evaluates to$false. - The function hits the
elsebranch and returns$item—the array containing both 'a' and your dictionary. When this array outputs to the console, the dictionary element is displayed prominently, making it look like the entire dictionary is the return value.
The fix: Correct function call syntax
To pass two separate parameters to your function, use PowerShell's standard syntax—space-separated values, no enclosing parentheses:
foo 'a' $dict
If you really prefer using parentheses (though it's not idiomatic PowerShell), you'd need to wrap each parameter individually:
foo ('a') ($dict)
With the correct call, $item will be 'a', $dict_of_item will be your dictionary. The condition $dict_of_item.keys -contains 'a' will evaluate to $true, and the function will return the expected value 1.
内容的提问来源于stack exchange,提问作者Максим Ототюк

