Powershell hash table issue

I am writing a script to take a string of letters and convert them to phonetic values. The problem I am facing is that I cannot reference the value in the hash table (see Error below). I'm not sure why, because the code looks good 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]
}
+3
source share
3 answers

Every Char is a Rich Object, Change:

write-host $ alphabet [$ char]

to

write-host $ alphabet ["$ char"]

or

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

+4
source

Your problem is that the $alphabet[$char]value $charis null. Where from $chararray?

0
source

, . Alfa, Juliett (sp) .

$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

Source: https://habr.com/ru/post/1751909/


All Articles