Adam
Adam

Reputation: 2031

How to add a member to an existing PowerShell object?

The following powershell gets an object of Computer System information:

> $o = Get-WmiObject -Class Win32_ComputerSystem -ComputerName .
> $o

# output

# Domain              : somedomain.com
# Manufacturer        : VMware, Inc.
# Model               : VMware Virtual Platform
# Name                : MYSERVER
# PrimaryOwnerName    : Windows User
# TotalPhysicalMemory : 17179332608

I add a new member TotalPhysicalMemoryGB to the object $o, as follows:

> $o = Add-Member -Input $o @{TotalPhysicalMemoryGB=([math]::round($t.TotalPhysicalMemory / 1GB))} -PassThru

This appears to work as I can access the member:

> $o.TotalPhysicalMemoryGB

# output
# 16

However, when I print the whole object again, the member TotalPhysicalMemoryGB does not appear in the member list:

> $o

# output

# Domain              : somedomain.com
# Manufacturer        : VMware, Inc.
# Model               : VMware Virtual Platform
# Name                : MYSERVER
# PrimaryOwnerName    : Windows User
# TotalPhysicalMemory : 17179332608

What am I doing wrong? How can I get the new member included when I print $o?

Upvotes: 2

Views: 508

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58981

You don't print the whole object by just output it to the console. There is a predefined view that specifies which properties of a System.Management.ManagementObject#root\cimv2\Win32_ComputerSystem is printed.

You can get a full list of all properties by using the Format-List cmdlet:

$o | Format-List *

Now you will find your previously added property.

As a workaround, you could also manually select the properties you want to output by using the Select-Object cmdlet:

$o | Select-Object Domain, Manufacturer, Model, Name, PrimaryOwnerName, TotalPhysicalMemory, TotalPhysicalMemoryGB

Upvotes: 2

Related Questions