Author Posts

June 14, 2015 at 10:52 am

Hello community,
I am wondering if I could use Foreach-Object cmdlet in order to take the object came from the pipeline and not only a property.

Thank you in advance!!!

June 14, 2015 at 11:22 am

CHARALABOS, the purpose for ForEach-Object to take in objects. Can you elaborate on why you ask this? Is there a specific situation you encounter?

June 14, 2015 at 11:36 am

My question came from that few minutes before I only found was a way to take each object PROPERTY every time.

But I just found that I can use Foreach-Object like this:
For example:

PS C:\> $processes = New-Object System.Collections.ArrayList
PS C:\> Get-Process | measure

Count : 68
Average :
Sum :
Maximum :
Minimum :
Property :

PS C:\> Get-Process | ForEach-Object { $a = $processes.Add($_) }
PS C:\> $processes.Count
68

With this I can get all processes running on my system and store each process (process object) and all of its properties in an arraylist I created above.

This was my question.

[good source here]:
http://blogs.technet.com/b/heyscriptingguy/archive/2014/07/08/getting-to-know-foreach-and-foreach-object.aspx

June 14, 2015 at 12:04 pm

But why would you do that? If you just do this: $a = Get-Process
Then variable $a is already a array of objects.

June 14, 2015 at 12:34 pm

Yes but I was looking a way to make progress bars to fill for every process coming from the pipeline !

June 14, 2015 at 5:27 pm

I agree with Richard, you are way over complicating it.

$a = Get-Process
$a.Count

Powershell cmd-lets typically return data in a PSObject. A PSObject is an array of objects. Even in the code you posted, you are piping the results of Get-Process to a foreach, indicating that it is already an array In the example below, we are manually creating a PSObject, similar to how Get-Process would build results:

$object = @()

$object += New-Object -TypeName PSObject -Property @{FirstName="Bill";LastName="Johnson"}
$object += New-Object -TypeName PSObject -Property @{FirstName="Sally";LastName="Smith"}

"Object Count: {0}" -f $object.Count

$object | Format-Table -AutoSize

Output:

Object Count: 2

LastName FirstName
-------- ---------
Johnson  Bill     
Smith    Sally