Monthly Archive

Categories

Creating objects

In my recent post about avoiding Add-Member I showed how to create objects. As with most things in PowerShell there are a number of different ways of creating objects.

I showed this code:

$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

 

A number of comments objected to this saying I should have used:

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

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

$op

 

In PowerShell v3 s you gained the option to directly create the object by using a type declaration as shown. There’s a couple of advantages – it’s slightly less typing and it preserves the order of the properties as if you’d used an ordered hashtable.

 

The disadvantage to my mind is that you have to remember to use [pscustomobject] which is a placeholder for PSObject. You have to do it this way because you’re effectively using the PSObject constructor with no parameters.

 

There are a number of reasons I didn’t use this technique. Firstly, a lot of my posts are for beginners and using New-Object is simpler to grasp then the type declaration on a hash table method. Secondly, remembering to use pscustomobject is a pain. if you forget it and use [psobject] you end up with a hash table as the output rather than the object you thought you were going to get.

 

Both techniques work but I prefer using New-Object because it’s easier to understand what’s going on in the code especially for people relatively new to PowerShell.

 

Where there are multiple good ways to complete a task in PowerShell I think its best to find a method that you’re comfortable with and use that. In reality both methods end up with the same result and comes down to personal preference. Don’t let anyone tell you one is better than the other!

Comments are closed.