powershell - 为什么函数返回null?

标签 powershell

我正在尝试将从函数返回的值分配给变量,但该变量仍然为空。为什么?

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()

最佳答案

需要注意的两件事 - 当您在 PowerShell 中调用 cmdlet 或函数时,位置参数不是以逗号分隔的:

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

其次,PowerShell 非常渴望枚举您沿管道传递的所有数组,因此当您这样做时:
return New-Object System.Collections.ArrayList

PowerShell 尝试输出 arraylist 中的所有单个项,但由于它是空的,因此不会返回任何内容!

您可以通过使用一元数组运算符 ( , ) 将 ArrayList 包装在数组中来规避此问题:
return ,$result

关于powershell - 为什么函数返回null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206656/

相关文章:

powershell - 在ps1中查找函数并调用

regex - 使用Powershell和Regex解析固定长度的字段文件,如何将空捕获组替换为零?

powershell - 将内容插入Powershell中的文本文件

Powershell递归搜索选择.txt文件,然后将所有文件的内容输出到单个.txt文件中

powershell - 应用 PowerShell DSC 配置时出错

PowerShell 区分大小写变量

c# - 从 C# 调用 COM 对象

xml - 如果使用 PowerShell 不存在,如何添加属性?

windows - 通过cmd/batch/powershell启用Windows 10内置热点

string - 解析没有空格的算术计算