Shinaolord
Shinaolord

Reputation: 167

$c.length just outputs a ton of one's, not the length

I've been trying to learn some PowerShell, and was playing around trying to make the following script (to take all Starttime values from Get-Process and save them in a form excluding the Time part of the DateTime Object.)

    $a=( Get-Process |Where-Object ProcessName -NotMatch 'Idle' | Select-Object -property starttime);

 #I think Select-Object part may not be necessary, but left in as that's how 
 #I've coded it

 $b= $a.starttime; 

$c=New-Object System.Collections.Generic.List[DateTime];

$count=0; @(0..($b.length-1)).foreach({ Write-Host $count,$b[$_].ToShortDateString(); $c.add($b[$_].ToShortDateString()); $count++ }) 

And I think it does what I intended it to do. Calling $b[j]-$c[j] produces only values of Minutes, Seconds, Milliseconds. However, when I call the lengths, I get the following

$b.length

175

$c.length

1

1

1

etc.,

So why is this? I'm not too versed in powershell (been playing with it for about a week), and I feel as though $c.length should spit out the same value as $b.length? What have I done in error?

Upvotes: 1

Views: 43

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174660

First off, the solution to this problem is straight-forward - use Count to obtain the total count of items in the list:

$c.Count

PowerShell, since version 4.0, supports something called "property enumeration", which means that when you reference a property name on an enumerable object (like a List[Datetime] for example) with the . member resolution operator, and the property doesn't exist on the referenced object, PowerShell will attempt to resolve that property name against the items contained in the enumerable object.

The generic List[] type doesn't have a Length property, hence the 175 individual results :)

Upvotes: 1

Related Questions