Determine if PowerShell function is running as part of a pipeline?

Posted by Richard Cook on Stack Overflow See other posts from Stack Overflow or by Richard Cook
Published on 2010-12-28T21:48:02Z Indexed on 2010/12/28 21:54 UTC
Read the original article Hit count: 251

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about powershell

Related posts about powershell-v2.0