开发者

Powershell pipelining only returns last member of collection

开发者 https://www.devze.com 2023-04-05 08:44 出处:网络
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 member

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)
{

Ne开发者_高级运维w-Object PSObject -Property @{
Name = $Process.Processname

}

} 
Get-Stats($Process)


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


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
    )
...


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消