I've a simple function:
function Write-Log {
[CmdletBinding()]
param (
# Lines to log
[Parameter(Mandatory , ValueFromPipeline )]
[AllowEmptyString()]
$messages
)
process {
Write-Host $_
}
}
Based on ValueFromPipeline
in can use the function with pipeline input, e.g.
"a","b", "c" | Write-Log
a
b
c
That's ok. But if I want to use my function in that way:
Write-Log -message "a", "b", "c"
the automatic $_
variable is empty, and nothing is printed.
I also found these two stackoverflow links:
- Handling pipeline and parameter input in a Powershell function
- How do I write a PowerShell script that accepts pipeline input?
Both of them suggest the following pattern:
function Write-Log {
[CmdletBinding()]
param (
# Lines to log
[Parameter(Mandatory , ValueFromPipeline )]
[AllowEmptyString()]
$messages
)
process {
foreach ($message in $messages){
Write-Host $message
}
}
}
Above pattern works for my use case. But from my point of view is feels weird to call foreach
in the `process´ block, since (as far as I've understood) the process block is called for every pipeline item. As there a better cleaner way to write functions supporting both use cases?
Thx.