Hind Forsum
Hind Forsum

Reputation: 10497

Powershell: Adding element to hashtable failed

PS C:\Users\Hind> $b=@{}
PS C:\Users\Hind> $b+={k="a";v="b"}
A hash table can only be added to another hash table.
At line:1 char:1
+ $b+={k="a";v="b"}
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : AddHashTableToNonHashTable

Why did it fail? How can I add one element to a hashtable successfully?

Upvotes: 4

Views: 10247

Answers (2)

bonm014
bonm014

Reputation: 41

Initialising the hashtable should be with round bracket instead of curly brackets

$b=@()
$b+=@{k="a";v="b"}

Upvotes: 3

Daniel Lesser
Daniel Lesser

Reputation: 211

Correction, this fails because you are missing the @ character in front of @{k="a";b="b"}

PS C:\Users\Hind> $b=@{}
PS C:\Users\Hind> $b+=@{k="a";v="b"}

@{} is declaring a new hash table. {} is a script block. They are not the same.

Upvotes: 5

Related Questions