4
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?

0

2 Answers 2

5

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.

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

5 Comments

So, can I append one hashtable to another? Any syntax like this? I'm not sure if Powershell supports any kind of operator overloading?
{} is just a closure in PowerShell without @{} and so the operands are of different types if @ is omitted.
i tried : D:\> $myhash=@{k1="va1";k2="val2"} PS D:\> $myhash+={k3="val3"} A hash table can only be added to another hash table. Still doesn't work?
$myhash+=@{k3="val3"}
@{} = declaring a new hash table. {} is a script block. They aren't the same.
3

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

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

Comments

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.