Updating Objects

suggest change

Adding properties

If you’d like to add properties to an existing object, you can use the Add-Member cmdlet. With PSObjects, values are kept in a type of “Note Properties”

$object = New-Object -TypeName PSObject -Property @{
        Name = $env:username
        ID = 12
        Address = $null
    }

Add-Member -InputObject $object -Name "SomeNewProp" -Value "A value" -MemberType NoteProperty

# Returns
PS> $Object
Name ID Address SomeNewProp
---- -- ------- -----------
nem  12         A value

You can also add properties with Select-Object Cmdlet (so called calculated properties):

$newObject = $Object | Select-Object *, @{label='SomeOtherProp'; expression={'Another value'}}

# Returns
PS> $newObject
Name ID Address SomeNewProp SomeOtherProp
---- -- ------- ----------- -------------
nem  12         A value     Another value

The command above can be shortened to this:

$newObject = $Object | Select *,@{l='SomeOtherProp';e={'Another value'}}

Removing properties

You can use the Select-Object Cmdlet to remove properties from an object:

$object = $newObject | Select-Object * -ExcludeProperty ID, Address

# Returns
PS> $object
Name SomeNewProp SomeOtherProp
---- ----------- -------------
nem  A value     Another value

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents