Thursday, January 03, 2008

A simple and clever way to create a custom object

In BS on Posh I found a simple and clever way to creating a custom object. Personally, I have been using one of these method -

$obj=New-Object object

Add-Member -InputObject $obj NoteProperty Column1 $null

Add-Member -InputObject $obj NoteProperty Column2 $null

Add-Member -InputObject $obj NoteProperty Column3 $null

$obj.Column1="Value1"

$obj.Column2="Value2"

$obj.Column3="Value3"

or -

$obj=1 | Select-Object @{Name="Column1";Expression={$null}},`

@{Name="Column2";Expression={$null}},`

@{Name="Column3";Expression={$null}}

$obj.Column1="Value1"

$obj.Column2="Value2"

$obj.Column3="Value3"

As BS shows in Using Switch -RegEx to create Custom Object (Getting HBA Info), you can do it much simpler -

$obj="" | Select-Object Column1,Column2,Column3

$obj.Column1="Value1"

$obj.Column2="Value2"

$obj.Column3="Value3"

I am aware that you can assign a value to the columns in the first two methods directly and thus make that code shorter. But typically, this construct is used in a loop and you often do not have the column values directly available. In these cases, the elegant Select-Object Column1,Colum2,Column3 is preferable.

A warning

Do not get trapped by using this construct/pattern -

function DoubleNumbersTest {

    $obj="" | Select-Object Number,DoubleNumber

    1..10 | % {

        $obj.Number=$_

        $obj.DoubleNumber=$_*2

        $obj

    }

}

When you look at the output, it may seem fine, but if you use the output objects for something, you will realize, that you in fact only have a single object. An object must be created for each output. Try it yourself -

DoubleNumbersTest # seems fine

$numbers=DoubleNumbersTest

$numbers # what a strange output ;)

2 comments:

Shay Levy said...

To overcome the last gotcha move the object creation inside the loop:

function DoubleNumbersTest($n){
1..$n | % {
$obj="" | Select-Object Number,DoubleNumber
$obj.Number=$_
$obj.DoubleNumber=$_*2
$obj
}
}

# create 10 objects
DoubleNumbersTest 10

-----
Shay Levi
$cript Fanatic
http://scriptolog.blogspot.com

Per Østergaard said...

To $hay: Just as I tried to say ;)