27

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.

2
  • 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
    Commented Mar 24, 2016 at 13:07
  • 1
    I feel like marking this as a dupe: stackoverflow.com/questions/17353797/…
    – Matt
    Commented Mar 24, 2016 at 13:11

2 Answers 2

30

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}}
20

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.