Search code examples
powershellpipelinepowershell-5.0

Show Last Object From Pipline


I have a PowerShell function (Out()). When I want to get a result, it takes the last object from the pipline. For example: I want to show all objects in (gps):

function Out() {
    [CmdletBinding()]
    [Alias()]
    Param(
        [Parameter(Mandatory=$false,
                   ValueFromPipeline=$true,
                   Position=0)]
        $Out
    )
    $Out
}

Result:

PS C:\> gps | Out

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName          
-------  ------    -----      -----     ------     --  -- -----------          
    505      27     7796       6220       0.78  13160   0 wmpnetwk 

Solution

  • Put the output in a Process {} block:

    function Out() {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory=$false, ValueFromPipeline=$true, Position=0)]
            $Out
        )
    
        Process {
            $Out
        }
    }
    

    That block is invoked for each object received from the pipeline.

    From the documentation:

    Process

    This block is used to provide record-by-record processing for the function. This block might be used any number of times, or not at all, depending on the input to the function. For example, if the function is the first command in the pipeline, the Process block will be used one time. If the function is not the first command in the pipeline, the Process block is used one time for every input that the function receives from the pipeline. If there is no pipeline input, the Process block is not used.

    This block must be defined if a function parameter is set to accept pipeline input. If this block is not defined and the parameter accepts input from the pipeline, the function will miss the values that are passed to the function through the pipeline.