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!!!
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!!!
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?
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.
But why would you do that? If you just do this: $a = Get-Process
Then variable $a is already a array of objects.
Yes but I was looking a way to make progress bars to fill for every process coming from the pipeline !
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