Monthly Archive

Categories

Bad habits when creating objects

I’m seeing a lot of code recently that looks like this

 

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

$obj  = New-Object -TypeName PSObject

$obj | Add-Member -MemberType NoteProperty -Name Name -Value $comp.Name
$obj | Add-Member -MemberType NoteProperty -Name  Manufacturer -Value $comp.Manufacturer
$obj | Add-Member -MemberType NoteProperty -Name Model -Value $comp.Model
$obj | Add-Member -MemberType NoteProperty -Name OS -Value $os.Caption
$obj | Add-Member -MemberType NoteProperty -Name SP -Value $os.ServicePackMajorVersion
$obj | Add-Member -MemberType NoteProperty -Name Architecture -Value $os.OSArchitecture

$obj

 

A couple of calls to CIM classes then a long laborious way to create an output object.  Way, way, way back in the day you had to create objects like this. Life and PowerShell have moved on.

 

There are much simpler ways to get the job done that involve far less typing. The more you type the greater the chance of introducing an error. Debugging a mass of Add-member calls is not something you ever want to do.

 

So easy way number 1.

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

$props = @{
'Name' = $comp.Name
'Manufacturer' = $comp.Manufacturer
'Model' = $comp.Model
'OS' = $os.Caption
'SP' = $os.ServicePackMajorVersion
'Architecture' = $os.OSArchitecture

}
$obj  = New-Object -TypeName PSObject -Property $props

$obj

 

Create a hash table of the properties you want your object to have and pass that to New-Object. I prefer to create the hash table as a separate step as I find it easier to read.

This is far, far quicker than multiple calls to Add-Member. Its also safer as there’s a lot less to type.

 

You can make the process a bit simple – easy way number 2:

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

$obj = [PSCustomObject]@{
'Name' = $comp.Name
'Manufacturer' = $comp.Manufacturer
'Model' = $comp.Model
'OS' = $os.Caption
'SP' = $os.ServicePackMajorVersion
'Architecture' = $os.OSArchitecture

}

$obj

 

Create the object directly from the hash table – note that you have to make the type PSCustomObject not PSObject.

There’s no excuse for creating objects with multiple calls to Add-Member

Comments are closed.