Determine if PowerShell function is running as part of a pipeline?
- by Richard Cook
Can a PowerShell function determine if it is being run as part of a pipeline? I have a function which populates an array with instances of FileInfo which I would like to "yield" to the pipeline if the function is being run this way or produce some pretty output if the function is being invoked by itself from the command line.
function Do-Something {
$file_infos = @()
# Populate $file_infos with FileInfo instances...
if (INVOKED_IN_PIPELINE) {
return $file_infos
}
else {
foreach ($file_info in $file_infos) {
write-host -foregroundcolor yellow $file_info.fullname
}
}
}
Basically, I'm trying to figure out how to implement INVOKED_IN_PIPELINE. If it is run in a pipeline (e.g. Do-Something | format-table fullname), I would simply yield the array, but if run directly (e.g. Do-Something), it would simply pretty-print the output.
Is there a way to do this? If there is a more "idiomatic" way to achieve this kind of thing, I would also be interested to know.