Powershell哈希表问题

时间:2010-06-26 17:42:08

标签: powershell

我正在编写一个脚本来取一串字母并将它们转换为语音值。我遇到的问题是我无法在哈希表中引用一个值(请参阅下面的错误)。我不确定为什么代码看起来很好。

Index operation failed; the array index evaluated to null.
At C:\Scripts\test.ps1:8 char:23
    + write-host $alphabet[ <<<< $char]
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex

}

param($ string = $(throw'输入字符串'))

$alphabet = @{
"A" = "Alfa";
"B" = "Bravo ";
"C" = "Charlie ";
"D" = "Delta ";
"E" = "Echo ";
"F" = "Foxtrot ";
"G" = "Golf ";
"H" = "Hotel ";
"I" = "India ";
"J" = "Juliett";
"K" = "Kilo ";
"L" = "Lima ";
"M" = "Mike ";
"N" = "November ";
"O" = "Oscar ";
"P" = "Papa ";
"Q" = "Quebec ";
"R" = "Romeo ";
"S" = "Sierra ";
"T" = "Tango ";
"U" = "Uniform ";
"V" = "Victor ";
"W" = "Whiskey ";
"X" = "X-ray";
"Y" = "Yankee ";
"Z" = "Zulu ";
}

clear-host
$charArray = $string.ToCharArray()
foreach ($char in $charArray)
{
    write-host $alphabet[$char]
}

3 个答案:

答案 0 :(得分:5)

每个Char都是一个丰富的对象,更改:

write-host $ alphabet [$ char]

write-host $ alphabet [“$ char”]

write-host $ alphabet [$ char.ToString()]

答案 1 :(得分:0)

您的问题是$alphabet[$char]$char为空。 $chararray来自哪里?

答案 2 :(得分:-1)

你需要在数组中的每个字母后丢失空格。你也在Alfa,Juliett(sp)和X射线之后错过了一个空间。

$alphabet = @{
"A"  =  "Alfa ";
"B"  =  "Bravo ";
"C"  =  "Charlie ";
"D"  =  "Delta ";
"E"  =  "Echo ";
"F"  =  "Foxtrot ";
"G"  =  "Golf ";
"H"  =  "Hotel ";
"I"  =  "India ";
"J"  =  "Juliet ";
"K"  =  "Kilo ";
"L"  =  "Lima ";
"M"  =  "Mike ";
"N"  =  "November ";
"O"  =  "Oscar ";
"P"  =  "Papa ";
"Q"  =  "Quebec ";
"R"  =  "Romeo ";
"S"  =  "Sierra ";
"T"  =  "Tango ";
"U"  =  "Uniform ";
"V"  =  "Victor ";
"W"  =  "Whiskey ";
"X"  =  "X-ray ";
"Y"  =  "Yankee ";
"Z"  =  "Zulu ";
}