2017-02-02 12 views
1

これは非常に簡単です - 関数からハッシュテーブルの配列を返す必要があります。これは、複数のハッシュテーブルが存在する場合に機能しますが、1つしかない場合、結果は配列ではありません。私はむしろ、結果が配列であるかどうかをテストしません。PowerShellで単一要素の配列を返します

function GetArrayWith1Hashtable() 
{ 
    $array = @() 

    $hashtable = @{} 
    $hashtable["a"] = "a" 
    $hashtable["b"] = "b" 
    $hashtable["c"] = "c" 
    $array += $hashtable 

    Write-Host "GetArrayWith1Hashtable array.Length =" $array.Length 
    Write-Host "GetArrayWith1Hashtable array.Count" $array.Count 
    Write-Host "GetArrayWith1Hashtable array[0].Keys" $array[0].Keys 

    $array 
} 

function GetArrayWith2Hashtables() 
{ 
    $array = @() 

    $hashtable = @{} 
    $hashtable["a"] = "a" 
    $hashtable["b"] = "b" 
    $hashtable["c"] = "c" 
    $array += $hashtable 

    $hashtable2 = @{} 
    $hashtable2["d"] = "d" 
    $hashtable2["e"] = "e" 
    $hashtable2["f"] = "f" 
    $array += $hashtable2 

    Write-Host "GetArrayWith2Hashtables array.Length = " $array.Length 
    Write-Host "GetArrayWith2Hashtables array.Count = " $array.Count 
    Write-Host "GetArrayWith2Hashtables array[0].Keys =" $array[0].Keys 
    Write-Host "GetArrayWith2Hashtables array.Count = "$array[1].Keys 

    $array 
} 

$result1 = GetArrayWith1Hashtable 
# $result1.Length - not available 
Write-Host "Result of GetArrayWith1Hashtable result1.Count = " $result1.Count      # Count = 2 (would expect this to be 1) 
# $result1[0] not available - not an array 

$result2 = GetArrayWith2Hashtables 
Write-Host "Result of GetArrayWith2Hashtables result2.Length = " $result2.Length # Length = 2 
Write-Host "Result of GetArrayWith2Hashtables result2.Count = "  $result2.Count # Count = 2 
Write-Host "Result of GetArrayWith2Hashtables result2[0].Keys = "  $result2[0].Keys # Keys = c a b 
Write-Host "Result of GetArrayWith2Hashtables result2[1].Keys = "  $result2[1].Keys # Keys = d e f 

<# 
    FULL OUTPUT: 

GetArrayWith1Hashtable array.Length = 1 
GetArrayWith1Hashtable array.Count 1 
GetArrayWith1Hashtable array[0].Keys c a b 

Result of GetArrayWith1Hashtable result1.Count = 2 

GetArrayWith2Hashtables array.Length = 2 
GetArrayWith2Hashtables array.Count = 2 
GetArrayWith2Hashtables array[0].Keys = c a b 
GetArrayWith2Hashtables array.Count = d e f 

Result of GetArrayWith2Hashtables result2.Length = 2 
Result of GetArrayWith2Hashtables result2.Count = 2 
Result of GetArrayWith2Hashtables result2[0].Keys = c a b 
Result of GetArrayWith2Hashtables result2[1].Keys = d e f 

#> 

答えて

1

だけ配列に戻り値の型をキャスト:

$result1 = @(GetArrayWith1Hashtable) 
関連する問題