Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add more property values to a custom object

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.

like image 207
eodeluga Avatar asked Mar 24 '16 12:03

eodeluga


People also ask

How do I add a property to a PowerShell object?

The Add-Member cmdlet lets you add members (properties and methods) to an instance of a PowerShell object. For instance, you can add a NoteProperty member that contains a description of the object or a ScriptMethod member that runs a script to change the object.

How many custom object records can you have in HubSpot?

Please note: you can have up to ten unique value properties for each custom object in your HubSpot account. You'll use your defined properties to populate the following property-based fields: requiredProperties: the properties that are required when creating a new custom object record.

What is NoteProperty in PowerShell?

A NoteProperty is a static property name, often added by Select-Object or Add-Member . Finally, you might also see PropertySet . Think of this as a prepackaged bundle of properties. These are defined by PowerShell or cmdlet developers—for example, a process object as a PSResources property set.


1 Answers

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}}
like image 125
Ansgar Wiechers Avatar answered Sep 19 '22 07:09

Ansgar Wiechers