使用PowerShell获取哈希表中当前值的键

时间:2016-05-29 08:46:56

标签: powershell

我遇到了问题,看起来很简单,却无法找到解决方案;我在PowerShell中迭代一个哈希表,它看起来像这样:

foreach($tool in $otherTools.GetEnumerator() | Sort Name)
{
   #tried echo $tool.Name
   #tried echo $tool.Value
   #tried echo $tool.Key
}

但上面没有任何作品。 原因是我想按键内部使用switch语句。

HashTable看起来像:

Name                           Value
----                           -----
One                           testone
Two                           TestTwo

1 个答案:

答案 0 :(得分:4)

你做得对。也许您使用echo "$tool.Key"之类的内容输出System.Collections.DictionaryEntry.Key。要解决此问题,您可以使用echo "$($tool.Key)"或格式字符串:

$hashTable = @{
    One = 'testone'
    Two = 'TestTwo'
}

foreach ($tool in $hashTable.GetEnumerator() | sort Name)
{
    Write-Host ("Name: {0} Value: {1}" -f $tool.Key, $tool.Value)
}

输出:

Name: One Value: testone
Name: Two Value: TestTwo
相关问题