April 7, 2010

How to create a collection of custom objects ?

First you have to create a collection object :

$psobjectStrongName = (New-Object psobject).psobject.GetType().AssemblyQualifiedName
$Col = New-Object "System.Collections.ObjectModel.Collection``1[[$psobjectStrongName]]"

Than you have to add an item (object) to the collection.

Method 1 :

$colItem = New-Object psobject -Property @{ObjRef=1;AddedBy="New-Object"}
$Col.Add($colItem)
$colItem =$null

Method 2 :

$colItem = New-Object psobject
Add-Member -InputObject $colItem -MemberType noteproperty -Name ObjRef -Value 2
Add-Member -InputObject $colItem -MemberType noteproperty -Name AddedBy -Value "Add-Member"
$Col.Add($colItem)
$colItem =$null

Method 3 (my personnal favorite) :

$Col.add((New-Object psobject -Property @{ObjRef=3;AddedBy="add with New-Object"}))

Source : http://www.vistax64.com/powershell/25307-how-put-psobject-into-system-collections-objectmodel-collection.html

No comments:

Post a Comment