This is a useful template for starting a CmdLet that needs to work in a PipeLine or by passing parameters.
Processing is implemented in the processItem sub-function. All the “–ne $null” conditions handle the differences between pipeline and parameter invocation.
function Test-PipelineOrParm ($parm)
{
begin
{
function processItem($item)
{
# Implement processing in this function
"processItem $item"
}
if ($parm -ne $null)
{
foreach ($item in $parm)
{
"begin $(processItem $item)"
}
}
}
process
{
if ($_ -ne $null)
{
"process $(processItem $_)"
}
}
end
{
Write-Host "Done"
}
}
These two examples demonstrate calling the template.
Write-Host "Test Pipeline processing"
Get-ChildItem | Test-PipelineOrParm
Write-Host "Test Parm processing"
Test-PipelineOrParm $(Get-ChildItem)