PS Foreach-Object Get the Object

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 1 year, 4 months ago.

  • Author
  • #26420
    Profile photo of CHARALABOS

    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!!!

  • #26422
    Profile photo of Richard Diphoorn
    Richard Diphoorn

    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?

  • #26423
    Profile photo of CHARALABOS

    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

    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]:

  • #26425
    Profile photo of Richard Diphoorn
    Richard Diphoorn

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

  • #26432
    Profile photo of CHARALABOS

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

  • #26438
    Profile photo of Rob Simmers
    Rob Simmers

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

    $a = Get-Process

    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


    Object Count: 2
    LastName FirstName
    -------- ---------
    Johnson  Bill     
    Smith    Sally   

You must be logged in to reply to this topic.