Pipeline input

Enabling your functions to accept pipeline input can make them much more powerful. That is also possible by using the parameter attribute.

The mandatory component that you need to use is a script block called process. This block is executed for each element flowing down the pipeline. The following code sample shows how entire objects are passed down the pipeline:

function pipelineByValue
{
param
(
[Parameter(ValueFromPipeline)]
[string]
$Parameter
)

begin
{
$count = 0
}

process
{
$count ++
Write-Host $Parameter
}

end
{
Write-Host "$count values processed"
}
}

"a","b","c" | pipelineByValue

Accepting the pipeline input by value means that entire objects are bound to a parameter.

If the pipeline input is accepted by property name, it means that you can pipe arbitrary objects to a function, as long as they possess a property with the same name as your parameter. In the following code sample, the BaseName property of existing objects is used as a parameter value:

function pipelineByProperty
{
param
(
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$BaseName
)

begin
{
$count = 0
}

process
{
$count ++
Write-Host $BaseName
}

end
{
Write-Host "$count values processed"
}
}

Get-ChildItem | pipelineByProperty

The blocks called begin and end are executed before and after processing the pipeline. A very common use case is to establish a connection to a service in the begin block, execute actions in the process block, and tear down the connection in the end block.

..................Content has been hidden....................

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