makerofthings7
makerofthings7

Reputation: 61463

Powershell pipelining only returns last member of collection

I have an issue running the following script in a pipeline:

Get-Process | Get-MoreInfo.ps1

The issue is that only the last process of the collection is being displayed. How do I work with all members of the collection in the following script:

param(    [Parameter(Mandatory = $true,ValueFromPipeline = $true)]
    $Process
)

function Get-Stats($Process)
{

New-Object PSObject -Property @{
Name = $Process.Processname

}

} 
Get-Stats($Process)

Upvotes: 1

Views: 282

Answers (3)

Michael Sorens
Michael Sorens

Reputation: 36708

Actually, both Christian's answer and tbergstedt's answer are both valid--and they are essentially equivalent. You can learn more about how and why in my recent article on Simple-Talk.com: Down the Rabbit Hole- A Study in PowerShell Pipelines, Functions, and Parameters.

In a nutshell, here are the salient points:

  1. A function body includes begin, process, and end blocks.
  2. A function not explicitly specifying any of the above 3 blocks operates as if all code is in the end block; hence the result you initially observed.
  3. A filter is just another way to write a function without any of the above 3 blocks but all the code is in the process block. That is why the above two answers are equivalent.

Upvotes: 0

Torbjörn Bergstedt
Torbjörn Bergstedt

Reputation: 3429

I you simply create Get-MoreInfo as a Filter instead of Function, you will get the desired effect.

Filter Get-MoreInfo
{
    param(    [Parameter(Mandatory = $true,ValueFromPipeline = $true)]
         $Process
    )
...

Upvotes: 0

CB.
CB.

Reputation: 60918

try this:

param(    [Parameter(Mandatory = $true,ValueFromPipeline = $true)]
    $Process
)

process{
New-Object PSObject -Property @{
Name = $Process.Processname}
}

Edit:

if you need a function:

function Get-MoreInfo {
param(    [Parameter(Mandatory = $true,ValueFromPipeline = $true)]
    $Process
)


process{
New-Object PSObject -Property @{
Name = $Process.Processname}
}

}

then you can use:

. .\get-moreinfo.ps1 # 

Get-Process | Get-MoreInfo

Edit after Comment:

Read about dot sourcing a script

Upvotes: 1

Related Questions