22

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
eodeluga
  • 608
  • 2
  • 7
  • 20
  • 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 Mar 24 '16 at 13:07
  • 1
    I feel like marking this as a dupe: http://stackoverflow.com/questions/17353797/powershell-how-to-initialize-array-of-custom-objects – Matt Mar 24 '16 at 13:11

2 Answers2

26

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}}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
18

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
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • Fantastic. Thanks. I'll mark that as the answer when the timeout expires. – eodeluga Mar 24 '16 at 13:06
  • 3
    @ATtheincredibleaf Your question was about adding property values? This answer is showing how to build an object array – Matt Mar 24 '16 at 13:08
  • 1
    I would build this in a loop and avoid the `+=`. Are you limited to PowerShell 2.0? – Matt Mar 24 '16 at 13:09
  • 1
    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 – Martin Brandl Mar 24 '16 at 13:11