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:
- A function body includes begin, process, and end blocks.
- 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.
- 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.
精彩评论