powershellpipeline

Is there a way to add more variables to the pipeline from the 'begin' section of a script?


Is there a way to dynamically add more variables to the pipeline in the "begin" section of a script?

I have a script which can accept data in three different ways:

  1. Value as parameter
  2. Pipe in values from another PowerShell command
  3. Accept a file with a list of values

Regardless of which source the data comes from, the type of values are the same and I'll be preforming the same actions on them.

I could just encapsulate all the behaviour I want into a function and use that on the data regardless of source, but I'm curious if there's some way to pull off the following:

param(
    [Parameter(ValueFromPipeline)]
    [string] $value,
    [string] $pathToFile
)
begin{
    if($pathToFile){
        $valuesFromFile = Get-Content $pathToFile

        # Add-ToPipeline is fake, but this is the idea I'm going for
        Add-ToPipeline $valuesFromFile
    }
}
process{
    # Steps to be done on each value
}

Basically I want to take the values from the file and tack them on to any values already in the pipeline so they all get processed in the same way. Is this possible, or am I fundamentally misunderstanding how pipelines work?


Solution

  • A way to achieve what you're looking for is to pipe the output from Get-Content directly to the invocation of the command's ScriptBlock, this is done by accessing MyInvocation automatic variable then refencing MyCommand property, which in this case is an instance of FunctionInfo and from there the ScriptBlock property.

    Do note though, this is an unconventional approach, and others reviewing your function might find it unclear why you chose this method. You should also note this will count as 2 different invocations of the same script block when -PathToFile is used.

    param(
        [Parameter(ValueFromPipeline)]
        [string] $Value,
        [string] $PathToFile
    )
    
    begin {
        if ($PathToFile) {
            # this will be the first incoming input
            Get-Content $PathToFile | & $MyInvocation.MyCommand.ScriptBlock
        }
    }
    process {
        $Value
    }