我在Powershell中有两个数组:
$headings = ['h1', 'h2']
$values = [3, 4]
保证两个数组的长度相同。如何创建一个数组,其中$headings
的值成为$values
数组的标题?
我希望能够做这样的事情:
$result['h2'] #should return 4
更新:
数组$headings
和$values
的类型为System.Array
。
答案 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:我只是给您逻辑上的起点,并在哈希表部分方面为您提供帮助。代码由您决定。