Home:ALL Converter>new-object psobject add value

new-object psobject add value

Ask Time:2012-09-04T20:55:16         Author:Bluz

Json Formatter

I understand that custom objects are created like this :

$obj=new-object psobject

and then I understand that you can add members (and values) like this :

$obj | Add-Member noteproperty name Jeff

Now the question is, how do you populate the object, add and remove "rows" of values ?

The only way around I found is to create an array and then push objects inside it, like this :

$array = @()
$array+=new-object PSObject -Property @{Name="Jeff"}
$array+=new-object PSObject -Property @{Name="Joe"}
$array+=new-object PSObject -Property @{Name="John"}

etc..

Is there a straight forward way to "increment" the values of the members in an object ?

$obj+=(Name=John) 

doesn't work.

Thanks

Author:Bluz,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12263938/new-object-psobject-add-value
Chui Tey :

A very late response, but I hope it helps someone who needs to count objects.\n\nLet's start with a list of users we wish to count.\n\n> $users = 1..10 | % {New-object psobject -Property @{ Name = \"User $_\"; Age = $_ } }\n> $users\nAge Name\n--- ----\n 1 User 1\n 2 User 2\n 3 User 3\n 4 User 4\n 5 User 5\n 6 User 6\n 7 User 7\n 8 User 8\n 9 User 9\n 10 User 10\n\n\nTo count them, put them into a hash table of counters\n\n > # Create hash table\n > $counter = @{}\n > # Assign users as keys in the table\n > $users | % { $counter.Add($_, 0) }\n > $counter\nName Value\n---- -----\n@{Age=4; Name=User 4} 0\n@{Age=1; Name=User 1} 0\n@{Age=3; Name=User 3} 0\n@{Age=5; Name=User 5} 0\n@{Age=10; Name=User 10} 0\n@{Age=9; Name=User 9} 0\n@{Age=8; Name=User 8} 0\n@{Age=7; Name=User 7} 0\n@{Age=6; Name=User 6} 0\n@{Age=2; Name=User 2} 0\n\n\nThen you can increment the counter whenever you encounter\nthe user in your script. For example, to increment \"User 1\" twice\nand \"User 4\" once\n\n> $counter[$users[0]] += 1\n> $counter[$users[0]] += 1\n> $counter[$users[3]] += 1\n> $counter\n\nName Value\n---- -----\n@{Age=4; Name=User 4} 1\n@{Age=1; Name=User 1} 2\n@{Age=3; Name=User 3} 0\n@{Age=5; Name=User 5} 0\n@{Age=10; Name=User 10} 0\n@{Age=9; Name=User 9} 0\n@{Age=8; Name=User 8} 0\n@{Age=7; Name=User 7} 0\n@{Age=6; Name=User 6} 0\n@{Age=2; Name=User 2} 0\n",
2018-08-24T01:08:38
yy