End

The end block executes after process has acted on all objects in the input pipeline.

The end block cannot use the $_ automatic variable. Parameters that accept pipeline input will be filled with the last value from the process block:

function Show-Pipeline {
begin {
$position = $myinvocation.PipelinePosition
Write-Host "Pipeline position ${position}: Start"

}

process {
Write-Host "Pipeline position ${position}: $_"
$_
}

end {
Write-Host "Pipeline position ${position}: End"
}
}

Running this command in a pipeline shows the end executing after all items in the input pipeline have been processed:

PS> $result = 1..2 | Show-Pipeline
Pipeline position 1: Start
Pipeline position 1: 1
Pipeline position 1: 2
Pipeline position 1: End

Commands that make extensive use of the end block include Measure-Object, ConvertTo-Html, and ConvertTo-Json. Such commands cannot return output until the end because the output is only valid when complete. The same is true of any other command that must gather input during a process, and output something on completion.

A simple command to count the number of elements in an input pipeline is shown here. The process block is unable to determine this; it must run again and again until the input pipeline is exhausted:

function Measure-Item {
begin {
$count = 0
}

process {
$count++
}

end {
$count
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.235.225