4

I'm writing a script to take a string of letters and convert them to phonetic values. The problem I'm having is that I am unable to reference a value in a hashtable (see error below). I'm not sure why as the code looks fine to me.

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 'Enter a string'))

$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
  • 1
    Alfa should be Alpha ;-) Commented Apr 4, 2011 at 21:17

3 Answers 3

7

Each Char is a rich object, Change:

write-host $alphabet[$char]

to

write-host $alphabet["$char"]

or

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

Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is that in $alphabet[$char], $char is null. Where does $chararray come from?

3 Comments

Sorry, the line where I created the char array was missing when I pasted in the code. I've added it back in now
That's not going to work; $alphabet's keys are strings, while $char is a char. You want $alphabet[$char.ToString()], but it still doesn't explain where the null comes from.
$alphabet[$char.ToString()] did the trick. Now it's working, thanks.
-1

Methinks you need to lose the space after each letter in your array. And you are also missing a space after Alfa, Juliett (sp), and X-ray.

$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 ";
}

1 Comment

Thanks for pointing that out. But that was a error with the i formatted the post. The original code doesn't have any spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.