2010-06-26 132 views
3

我正在編寫一個腳本來取一串字母並將它們轉換爲音標值。我遇到的問題是我無法在散列表中引用值(請參閱下面的錯誤)。我不確定爲什麼代碼對我來說很好。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 

} 

參數($字符串= $(扔 '輸入字符串'))

$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] 
} 
+1

Alfa應該是Alpha ;-) – x0n 2011-04-04 21:17:24

回答

4

每個字符是一個豐富的對象,更改:

寫主機$字母[$字符]

寫主機$字母[ 「$字符」]

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

-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 "; 
} 
+0

謝謝你指出。但是,這是我格式化該帖子的錯誤。原始代碼沒有任何空格。 – SuperFurryToad 2010-06-26 18:04:48

0

你的問題是,在$alphabet[$char]$char爲空。 $chararray從哪裏來?

+0

對不起,當我粘貼代碼時,我創建char數組的行已經丟失。我已經將它添加回現在 – SuperFurryToad 2010-06-26 18:14:14

+2

這不會起作用; '$ alphabet'的鍵是字符串,而'$ char'是一個字符。你想''字母表[$ char.ToString()]',但它仍然不能解釋null來自哪裏。 – Gabe 2010-06-26 18:27:29

+0

$ alphabet [$ char.ToString()]完成了這個訣竅。現在它工作,謝謝。 – SuperFurryToad 2010-06-26 18:48:46