Peculiar issue with powershell Hashtable and array -
i working on today , during testing noticed peculiar issue
$arry = @() $msg = @{body="this sample message";} $msg.brokerproperties=@{} $msg.brokerproperties.label= "msg1" $arry += $msg $arry | convertto-json # 1st result $msg.brokerproperties=@{} $msg.brokerproperties.label= "msg2" $arry += $msg $arry | convertto-json
the 1st result of $arry | convertto-json
below
{ "body": "this sample message", "brokerproperties": { "label": "msg1" } }
the 2nd result of $arry | convertto-json
below
[ { "body": "this sample message", "brokerproperties": { "label": "msg2" } }, { "body": "this sample message", "brokerproperties": { "label": "msg2" } } ]
what thought happen when set $msg.brokerproperties.label= "msg2"
2nd time , effect 2nd hashtable in array. interestingly property getting injected on 1st hashtable.
can please explain behaviour?
i doing in loop prepare json payload sending on api call,so lookign way update labels each inner within json object
hashtables passed by reference rather by value.
to create new hashtable existing hashtable, use clone()
:
$arry += [hashtable]$msg.clone()
be warned creates shallow clone, if have nested hashtables, inner entries still reference types, , depending on circumstances, you'd might want write own cloning function
Comments
Post a Comment