Shiju Samuel
Shiju Samuel

Reputation: 1591

Pipeline formatting Issue

I am trying to format the objects coming from the pipeline as below

function Format-Nice
{
        [CmdletBinding()] param(
            [Parameter(ValueFromPipeline=$true)]$objects
        )
        process {
            $objects | Format-Table -Property Name, 
            @{Label='Size';expression={[int]($_.Length/1MB) }}
        }
}

However, this seems to be breaking each object from the pipeline in a separate table on shell. I intent to write a generic format function which will will provide a custom hashtable expression depending upon the current object type in the pipeline.

Upvotes: 0

Views: 108

Answers (1)

user4003407
user4003407

Reputation: 22132

You need to use SteppablePipeline, so you does not run new copy of Format-Table for each input object:

function Format-Nice
{
    [CmdletBinding()] param(
        [Parameter(ValueFromPipeline=$true)][PSObject]$InputObject
    )
    begin {
        $SteppablePipeline={
            Format-Table -Property Name,
            @{Label='Size';expression={[int]($_.Length/1MB) }}
        }.GetSteppablePipeline($MyInvocation.CommandOrigin);
        $SteppablePipeline.Begin($PSCmdlet)
    }
    process {
        if($MyInvocation.ExpectingInput) {
            $SteppablePipeline.Process($InputObject)
        } else {
            $SteppablePipeline.Process()
        }
    }
    end {
        $SteppablePipeline.End()
        $SteppablePipeline.Dispose()
    }
}

Upvotes: 3

Related Questions