Powershell函数返回Array不是Hashtable

时间:2016-05-29 09:38:01

标签: powershell

我有一个我不明白的问题。我有一个看起来的功能:

Function hashTable
{
    Param($release)

    $releaseArray = @()
    if (![string]::IsNullOrWhitespace($release))
    {
        $releaseArray = $release.split("{|}", [System.StringSplitOptions]::RemoveEmptyEntries)
        $releaseArray.gettype() | Select-Object Name
        if($releaseArray.Count -gt 0) {
            $namePathArray = @{}
            foreach($namePath in $releaseArray) {
                $splitReleaseArray = $namePath.split("{,}", [System.StringSplitOptions]::RemoveEmptyEntries)
                $namePathArray.add($splitReleaseArray[0], $splitReleaseArray[1])
            }

            #here it echos propper hashtable

            $namePathArray.gettype() | Select-Object Name
            if($namePathArray.Count -gt 0) {
                #here it echos propper hashtable as well
                return $namePathArray
            }
        }
    }
}

但当我调用此函数时,我得到的数组不是哈希表,如下所示:

Name
----
String[]
test
reorder

示例输入参数:-release "reorder,c:\Repo\App|test,test"

我想知道我是否遗漏了什么?

1 个答案:

答案 0 :(得分:3)

您使用GetType() |Select Name语句有效地污染了输出流。删除它们,或使用Write-Host代替显示类型名称:

Function hashTable
{
    Param($release)

    $releaseArray = @()
    if (![string]::IsNullOrWhitespace($release))
    {
        $releaseArray = $release.split("{|}", [System.StringSplitOptions]::RemoveEmptyEntries)
        Write-Host ($releaseArray.gettype() | Select-Object -Expand Name)
        if($releaseArray.Count -gt 0) {
            $namePathArray = @{}
            foreach($namePath in $releaseArray) {
                $splitReleaseArray = $namePath.split("{,}", [System.StringSplitOptions]::RemoveEmptyEntries)
                $namePathArray.add($splitReleaseArray[0], $splitReleaseArray[1])
            }

            #here it echos propper hashtable

            Write-Host ($namePathArray.gettype() | Select-Object -Expand Name)
            if($namePathArray.Count -gt 0) {
                #here it echos propper hashtable as well
                return $namePathArray
            }
        }
    }
}