Home > Mobile >  Cannot set a string as a key for my hashtable
Cannot set a string as a key for my hashtable

Time:04-21

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 = @{ }

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

CodePudding user response:

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'
  • Related