Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot set a string as a key for my hashtable

I’m trying to set this string as my key:

a -long " string that - has. double and single quotes and dashes and dots

This string is the product of String Builder ToString() method.

The Hashtable is initialized like this: $myHashtable = @{ }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is the error: Cannot convert value "stringAbove" to type "System.Int32". Error: "Input string was not in a correct format."

I tried escaping the double quotation marks with a backtick. But got still the same error.

$resultFromToString = $myBuilder.ToString()
$myHashtable[$resultFromToString] = @{
  One = $one;
  Two = $two;
}

>Solution :

The error message implies that $myHashtable contains an array, not a hashtable.

  • To determine the actual type of $myHashtable, execute $myHashtable.GetType() or
    Get-Member -InputObject $myHashtable

This example shows that there’s no problem with your string, given that a string with any value – even '' – can serve as a hashtable key:

$myHashtable = @{} # Initialize.

$myHashtable['a - long string that has " and '' quotes and - and .'] = 'foo'

$myHashtable # Output

Output:


Name                           Value
----                           -----
a - long string that has " an… foo

As for what you tried:

By contrast, if $myHashtable is an array (irrespective of the type of its elements), your symptom surfaces, with any string value (that can’t be converted to an integer), given that only integers can serve as array indices:

$myHashtable = @{}, @{} # !! ARRRAY (of hashtables)

$myHashtable['some key'] = 'foo' # !! FAILS

Error output:

Cannot convert value "some key" to type "System.Int32". Error: "Input string was not in a correct format."

Note that, as the error message hints at, PowerShell automatically tries to convert a string index to an integer, so that something like the following does work, perhaps surprisingly:

# Same as: 
#   $myHashtable[0] = 'foo'
# because PowerShell automatically converts to [int]
$myHashtable[' -0 '] = 'foo'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading