How do you add more property values to a custom object

50,517

Solution 1

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

Solution 2

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}}
Share:
50,517
eodeluga
Author by

eodeluga

https://github.com/eodeluga

Updated on July 09, 2022

Comments

  • eodeluga
    eodeluga almost 2 years

    If I do this

    $account = New-Object -TypeName psobject -Property @{User="Jimbo"; Password="1234"}
    

    How do I add additional User and Password values to $account without overwriting the existing one?

    I cannot pre-populate $account from a hashtable. I don't know all the users and passwords at runtime.

    • Matt
      Matt about 8 years
      I think we need to see an example of what you are trying to do. Adding new properties is easier if you build the hash table before the new-object. $props = @{User="Jimbo"; Password="1234"}; $props.NewProperty = "Yeah"
    • Matt
      Matt about 8 years
      I feel like marking this as a dupe: stackoverflow.com/questions/17353797/…
  • eodeluga
    eodeluga about 8 years
    Fantastic. Thanks. I'll mark that as the answer when the timeout expires.
  • Matt
    Matt about 8 years
    @ATtheincredibleaf Your question was about adding property values? This answer is showing how to build an object array
  • Matt
    Matt about 8 years
    I would build this in a loop and avoid the +=. Are you limited to PowerShell 2.0?
  • Martin Brandl
    Martin Brandl about 8 years
    Matt is right, your question is a little bit misleading. I just figured out that you probably want to use an array because you want to store multiple user + pwd combinations