How do you add more property values to a custom object
The -Property
parameter of New-Object
takes a hashtable as argument. You can have the properties added in a particular order if you make the hashtable ordered. If you need to expand the list of properties at creation time just add more entries to the hashtable:
$ht = [ordered]@{ 'Foo' = 23 'Bar' = 'Some value' 'Other Property' = $true ...}$o = New-Object -Type PSObject -Property $ht
If you need to add more properties after the object was created, you can do so via the Add-Member
cmdlet:
$o | Add-Member -Name 'New Property' -Type NoteProperty -Value 23$o | Add-Member -Name 'something' -Type NoteProperty -Value $false...
or via calculated properties:
$o = $o | Select-Object *, @{n='New Property';e={23}}, @{n='something';e={$false}}
If you want to use $account
to store user + pwd credentials, you should declare it as an array
and add items when you want:
$account = @()$account += New-Object -TypeName psobject -Property @{User="Jimbo"; Password="1234"}$account += New-Object -TypeName psobject -Property @{User="Jimbo2"; Password="abcd"}$account += New-Object -TypeName psobject -Property @{User="Jimbo3"; Password="idontusepwds"}
Output of $account
:
User Password ---- -------- Jimbo 1234 Jimbo2 abcd Jimbo3 idontusepwds