Powershell使用一个数组的值作为另一个数组的标题

时间:2019-05-07 07:10:25

标签: arrays powershell

我在Powershell中有两个数组:

$headings = ['h1', 'h2']
$values = [3, 4]

保证两个数组的长度相同。如何创建一个数组,其中$headings的值成为$values数组的标题?

我希望能够做这样的事情:

$result['h2'] #should return 4

更新: 数组$headings$values的类型为System.Array

2 个答案:

答案 0 :(得分:2)

如上所述,您将需要PowerShell hashtable。通过@()在PowerShell中定义数组,有关更多信息,请参见about_arrays

$headings = @('h1', 'h2')
$values = @(3, 4)

$combined = @{ }

   if ($headings.Count -eq $values.Count) {
      for ($i = 0; $i -lt $headings.Count; $i++) {
         $combined[$headings[$i]] = $values[$i]
      }
}
else {
   Write-Error "Lengths of arrays are not the same"
}

$combined

转储combined的内容将返回:

$combined

Name                           Value
----                           -----
h2                             4
h1                             3

答案 1 :(得分:1)

尝试这样的事情:

$hash = [ordered]@{ h1 = 3; h2 = 4}
$hash["h1"] # -- Will give you 3

## Next Approach
$headings = @('h1', 'h2') #array
$values = @(3, 4) #array

If($headings.Length -match $values.Length) 
{
    For($i=0;$i -lt $headings.Length; $i++) 
    {
      #Formulate your Hashtable here like the above and then you would be able to pick it up
      #something like this in hashtable variable $headings[$i] = $values[$i]
    }

}

PS:我只是给您逻辑上的起点,并在哈希表部分方面为您提供帮助。代码由您决定。