PowerShell for Windows Admins

Jun 19 2018   10:57AM GMT

Avoid Add-Member

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

There’s a huge amount of code still being created that looks like this:

$os = Get-WmiObject -Class Win32_OperatingSystem
$comp = Get-WmiObject -Class Win32_ComputerSystem

$op = New-Object -TypeName PSObject |
Add-Member -MemberType NoteProperty -Name OS -Value $os.Caption -PassThru |
Add-Member -MemberType NoteProperty -Name Version -Value $os.Version -PassThru |
Add-Member -MemberType NoteProperty -Name Name -Value $comp.Caption -PassThru |
Add-Member -MemberType NoteProperty -Name Manufacturer -Value $comp.Manufacturer -PassThru |
Add-Member -MemberType NoteProperty -Name Model -Value $comp.Model -PassThru

$op

Some data is acquired and a custom object is created for the output. In this case an empty object is created and Add-Member is used to create and populate the object’s properties.

The best thing that can be said about this method is that it works. This method is a hang over from the early days of PowerShell. It’s about time that people moved on and learned how to do this properly.

NOTE: Get-CimInstance should be used these days instead of Get-WmiObject as the WMI cmdlets aren’t available in PowerShell v6.0 and are effectively deprecated.

Instead of using Add-Member use a hash table to create and populate the properties:

$os = Get-CimInstance -ClassName Win32_OperatingSystem
$comp = Get-CimInstance -ClassName Win32_ComputerSystem

$props = @{
OS = $os.Caption
Version = $os.Version
Name = $comp.Caption
Manufacturer = $comp.Manufacturer
Model = $comp.Model
}

$op = New-Object -TypeName PSObject -Property $props

$op

This is much cleaner, involves less typing (therefore reducing errors) and is easier to understand.

Many people (including those that should know better) whine about the fact that using New-Object means that the order of the properties when displayed isn’t the same as input and so prefer the Add-Member method.

If you absolutely have to force the order of properties then use an ordered hash table:

$os = Get-CimInstance -ClassName Win32_OperatingSystem
$comp = Get-CimInstance -ClassName Win32_ComputerSystem

$props = [ordered]@{
OS = $os.Caption
Version = $os.Version
Name = $comp.Caption
Manufacturer = $comp.Manufacturer
Model = $comp.Model
}

$op = New-Object -TypeName PSObject -Property $props

$op

So, should Add-Member be totally avoided. Not quite. It does have a use – when you want to add a very small number of properties to an existing object. Otherwise don’t use it.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: