header image

Avoid Add-Member

Posted by: | June 19, 2018 Comments Off on Avoid Add-Member |

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.

under: PowerShell

Comments are closed.

Categories