Powershell Custom Objects: How To Acess NoteProperty of collected result

icnivad picture icnivad · Apr 28, 2011 · Viewed 10.8k times · Source

Reading through an Article about custom Objects:

http://technet.microsoft.com/en-us/library/ff730946.aspx

I wonder why i get a result for the individual entry: e.g $objAverage.Name

while by $colAverages.Name nothing is returened. Although with Get-Member both show the [System.Object] NoteProperty Name

I would expect returning the all Names of my resultset in $colAverages.

Code of the article: C:\Temp\base.txt

Name,AtBats,Hits
Ken Myer,43,13
Pilar Ackerman,28,11
Jonathan Haas,37,17
Syed Abbas,41,20
Luisa Cazzaniga,22,6
Andrew Cencini,35,11
Baris Cetinok,19,4

Powershell:

$colAverages = @()

$colStats =Import-Csv C:\Temp\base.txt

foreach ($objBatter in $colStats)
  {
    $objAverage = New-Object System.Object
    $objAverage | Add-Member -type NoteProperty -name Name -value $objBatter.Name
    $objAverage | Add-Member -type NoteProperty -name BattingAverage -value ("{0:N3}" -f ([int] $objBatter.Hits / $objBatter.AtBats))
    $colAverages += $objAverage
  }

$colAverages | Sort-Object BattingAverage -descending

Answer

JPBlanc picture JPBlanc · Apr 28, 2011

Try $colAverages[0].name

for ($i=0 ; $i -le $colAverages.Length ; $i++)
{
  $colAverages[$i].name
}

Or

foreach ($a in $colAverages)
{
  $a.name
}

---------- EDIT----------

PS C:\> $colAverages.GetType()

IsPublic IsSerial Name                     BaseType                                                
-------- -------- ----                     --------                                                
True     True     Object[]                 System.Array                                            


PS C:\> $objAverage.GetType()

IsPublic IsSerial Name                     BaseType                                                
-------- -------- ----                     --------
True     True     Oject