Skip to content

Tee-Object -Process #20123

Open
Open

Description

Summary of the new feature / enhancement

Tee-Object could use a new parameter Process, accepting a scriptblock which will be invoked for every item going through it. Example usecases:

Proposed technical implementation details (optional)

Opens:

  1. Is there some magic we use to split and connect pipes, so that it correctly calls Begin, Process, End? Without it, we may either accidentally call the cmdlet for each object separately, causing each of them to clobber the last. This means we cannot simply implement it as ForEach-Item { $_ | $Process; $_ }:
    > 0..4 | ConvertTo-Json
    [
    	0,
    	1,
    	2,
    	3,
    	4
    ]
    > 0..4 | %{ ConvertTo-Json }
    0
    1
    2
    3
    4
  2. Similarly, if we first bulk all of the piped items and only later push them into the secondary pipe, this will break streaming, as with implementation with: ForEach-Object -Begin { $pipe = [List[object]]:new() } -Process { $pipe.Add($_); $_ } -End { $pipe | $Process }. It will be especially visible with usecase 1.: Tee-Object -Process { Write-Host } will only start outputting once the main pipeline has finished.
  3. How should we treat implicit or explicit output from the secondary pipe? Should it affect the primary pipe, should it be written to host, or should it be ignored? For ForEach-Object, the first is true, as can be seen with 0..4 | %{ $_; $_ } | Measure-Object outputting 10.
  4. If we can split the pipeline properly, do we have to worry about one part of it mutating the pipe for the other? In other words, what should be the order of execution of Process? Secondary pipe then primary, other way around, concurrent, undefined?
    Get-ChildItem | Tee-Object -Process { $_.Length = 123 } | ConvertTo-Json > files.json
    # Should the resulting JSON contain original Length, or all 123, as if with `ForEach-Object`?
    Get-ChildItem | Tee-Object -Process { ConvertTo-Json > files.json } | %{ $_.Length = 123 }
    # What if we switch main and secondary pipes around?
  5. Is the syntax I have been showing with scriptblock omitting $_ and pretending all the items are piped from the left even legal or reasonable? I don't see how to express some of the intentions I have shown without it, unless we make $_ in Tee-Object -Process { $_ | Export-Csv files.csv } mean the entire pipeline. Otherwise, maybe some new symbol like $% would make sense, as % is commonly already associated with item processing as default alias for ForEach-Object.

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Aug 16, 2023
  2. jhoneill commented on Aug 17, 2023

    @jhoneill

    Is the syntax I have been showing with scriptblock omitting $_ and pretending all the items are piped from the left even legal or reasonable? I don't see how to express some of the intentions I have shown without it, unless we make $_ in Tee-Object -Process { $_ | Export-Csv files.csv }

    YES
    { $_ | Export-Csv files.csv } and { $_} | Export-Csv files.csv are very different. The first writes each object to the file, and overwrites it with the next object. The second writes all the objects to a file.

    The more I've pushed this around, the more I think you need to have a second pipeline. "Tee" needs to push objects so that export-csv in this sees them as a sequence of input objects from the pipeline. And nothing can leak from pipeline that export-csv is in, back to the main one

    I've recycled some stuff I know from Proxy functions to create and run a steppable pipeline as a "Tee" or "Fork". There is probably a more elegant way of preventing the that pipeline sending data into the following command. but this is just a p.o.c :-)

    function Invoke-Fork {
        param( 
            [Parameter(Position=0,Mandatory=$true)]  
            [scriptblock]$forkBlock  ,
            [Parameter(ValueFromPipeline=$true)]
            $InputObect 
        )
        begin     { try {
                        $steppablePipeline = $forkBlock.GetSteppablePipeline($myInvocation.CommandOrigin)
                        $null = $steppablePipeline.Begin($PSCmdlet) } 
            catch { throw }
        }
        process   { try {$null  =  $steppablePipeline.Process($_) ;   Write-Output $_  }  catch { throw}}
        end       { try {$null  =  $steppablePipeline.End() } catch { throw }}
        clean     { if  ($null -ne $steppablePipeline) { $null = $steppablePipeline.Clean() }  }
    }

    So this works

    dir ~ | Invoke-Fork {Export-csv -Path $env:TEMP\stuff.csv  } | ft Name,Length
    

    and the block can be a multi-command pipeline

    dir ~ | Invoke-Fork {Select-Object -Property  name,LastWriteTime  |  Export-csv -Path $env:TEMP\stuff.csv  } | ft Name,Length
    

    My addition of | out-null works

    dir ~ | Invoke-Fork {Select-Object -Property  name,LastWriteTime  } | ft Name,Length
    

    Write-host works - what gets printed when is harder to follow.

    dir ~ | Invoke-Fork {Measure-Object -SUM LENGTH | % SUM | Write-Host } | ft Name,Length
    

    Roughly what you're looking to do ?

  3. dkaszews commented on Aug 18, 2023

    @dkaszews
    ContributorAuthor

    James O'Neill (@jhoneill) Will have to play around it, but this looks amazing 🤩

  4. mklement0 commented on Aug 18, 2023

    @mklement0
    Contributor

    A steppable pipeline looks promising, but note that Invoke-Fork doesn't prevent "pollution" of the pipeline with output from the script block at all, given that $steppablePipeline.Process($_) itself doesn't produce output and writes directly to the pipeline; in other words: $null = ... has no effect.

    PS> 1..3 | Invoke-Fork { % { -$_ } }
    -1
    1
    -2
    2
    -3
    3

    Assuming it is possible to capture the output from a steppable pipeline (which should then be a separate one), the logic could be as follows:

    • Silence the output by default (this would work with a save-to-file command such as Export-Csv) ...
    • ... unless -Variable or -FilePath are also specified, in which case capture the output in the specified variable or save it to the specified file.
    • Update: In combination with the new -Host switch (see Tee-Object should have a -Console parameter #19827), print directly to the host (display).
  5. dkaszews commented on Aug 18, 2023

    @dkaszews
    ContributorAuthor

    Michael Klement (@mklement0) How is Measure-Command implemented? Because I noticed that one does silence all output unless you explicitly pipe the measured command into Out-Default.

  6. mklement0 commented on Aug 18, 2023

    @mklement0
    Contributor

    Good question, Dominik Kowalski (@dkaszews).

    It uses the internal .InvokeWithPipe() method directly on the input ScriptBlock (-Expression argument), and uses a null pipe as the output (new Pipe { NullPipe = true }):

    Expression.InvokeWithPipe(
    useLocalScope: false,
    errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
    dollarUnder: InputObject, // $_
    input: Array.Empty<object>(), // $input
    scriptThis: AutomationNull.Value,
    outputPipe: new Pipe { NullPipe = true },
    invocationInfo: null);

    Note that the script block is invoked for every input object, with $_ bound to that object, as the following example demonstrates:

    1..3 | Measure-Command { $_ | Out-Host; pause }
  7. dkaszews commented on Aug 18, 2023

    @dkaszews
    ContributorAuthor

    Michael Klement (@mklement0) So while the PowerShell PoC is not able to replicate it, it should be relatively easy to do in the core C#?

    The whole idea behind this proposal was to replicate some of the stuff you can do in Linux with tee and process substitution. I wonder whether a better idea would be to port mkfifo and allow to do this kind of plumbing directly in PowerShell.

    Edit: sorry, I missed the last part. So the Measure-Command does not support streaming objects, which is the issue I mentioned in open 1., might be a dead end then.

  8. mklement0 commented on Aug 18, 2023

    @mklement0
    Contributor

    Dominik Kowalski (@dkaszews), if I understand correctly, what is needed is a steppable pipeline that is separate from the pipeline in which the enclosing command runs, is invoked input object by input object from the enclosing command's .ProcessRecord() method, and whose output can either be suppressed (by default) or collected (-Variable) or redirected to a file (-FilePath) separately.

    I'm not familiar enough with the SDK to know if this possible, but perhaps Patrick Meinecke (@SeeminglyScience) can weigh in.

  9. jhoneill commented on Aug 18, 2023

    @jhoneill

    That's odd. I posted a version of "invoke fork" with a kludged on addition of "| out-Null" (I referred to that here #20133 (comment) ) but it seems to have gone in editing the post. it was
    $forkblock = [scriptblock]::create( $forkblock.tostring() + ' | out-null' )

    I think there may be an important difference with Measure-Command because that isn't starting a pipe into which objects can be pushed.

  10. mklement0 commented on Aug 18, 2023

    @mklement0
    Contributor

    Good point - Out-Null can be integrated into the pipeline in the steppable script block, and the -FilePath and -Variable cases can be handled that way too - see the proof of concept below, which builds on the previous one (Invoke-WithFork).

    I suspect there is a more elegant way of creating the steppable script block with the added pipeline segments than basing it on the string representation of the input script block, which could have side effects.

    Note that the -Variable case sets the output variable via Set-Variable -Scope 1, which only works if the function isn't part of a script module (a moot point in a cmdlet implementation).

    Thus, you can do the following:

    $objects = [pscustomobject] @{ Num = 1 }, [pscustomobject] @{ Num = 2 }
    
    # Neither -FilePath nor -Variable specified: script-block output, if any, is discarded.
    $objects | Tee-WithProcess { Export-Csv out.csv } | 
      Out-Host
    
    '---'
    
    # Combination with the -Host switch: print the output to the host (display).
    $objects | Tee-WithProcess { Format-List } -Host  | 
      Out-Host
    
    '---'
    
    # -FilePath: Output (via Out-File) to the specified file
    # UPDATE: The p.o.c now treats a script block that doesn't contain a *single command*
    #        or single pipeline that *starts with a command*  implicitly as if it were enclosed 
    #        in `ForEach-Object`,  so no explicit use of the latter is needed anymore.
    $objects | Tee-WithProcess { -$_.Num  } -FilePath out.txt | 
      Out-Host
    
    '---'
    
    # -Variable: Output is collected in the specified variable ($out)
    $objects | Tee-WithProcess { -$_.Num  } -Variable out |
      Out-Host

    Tee-WithProcess source code:

    function Tee-WithProcess {
      param( 
        [Parameter(Position = 0, Mandatory)]  
        [scriptblock] $Process,
        [Parameter(ValueFromPipeline)]
        $InputObject,
        [string] $Variable,
        [string] $FilePath,
        [Alias('Host')] # Note: In a function implementation $Host cannot be used.
        [switch] $ToHost
      )
      begin {
        try {
          # Rule out mutually exclusive switches.
          if ((0, 1)[[bool] $Variable] + (0, 1)[[bool] $FilePath] + $ToHost.IsPresent -gt 1) { throw "-Variable, -FilePath, and -Host are mutually exclusive." }
          # Determine if the content of the script block is a single that statement comprising
          # either a single *command* or a single pipeline that *starts with* a command
          # which is assumed to *directly receive all pipeline input* (e.g, `Export-Csv`).
          # If not, assume it represents code to be run *for each input object*, 
          # with $_ reflecting each, and therefore wrap it in a ForEach-Object call.
          $isCommandPipeline =  ($Process.Ast.EndBlock.Statements.Count -eq 1 -and $Process.Ast.EndBlock.Statements[0].PipelineElements[0] -is [System.Management.Automation.Language.CommandAst])
          # NOTE: The implementation the block for the steppable pipeline via 
          #       recreation of the script block from its *string representation* in the single-command case
          #       is SUBOPTIMAL, but was chosen for simplicity in this proof-of-concept.
          $steppableScriptBlock = 
          [scriptblock]::Create($(
            if ($ToHost) {
              $isCommandPipeline ? 
                [scriptblock]::Create("$Process | Out-Host")
                : 
                { ForEach-Object -Process $Process | Out-Host }
            } elseif ($FilePath) {
              $isCommandPipeline ? 
                [scriptblock]::Create("$Process | Out-File -LiteralPath `"$FilePath`"")
                : 
                { ForEach-Object -Process $Process | Out-File -LiteralPath $FilePath }
            } elseif ($Variable) {
              $isCommandPipeline ? 
                [scriptblock]::Create("$Process | Write-Output -NoEnumerate -OutVariable aux | ForEach-Object -Process {} -End { Set-Variable -Scope 1 `"$Variable`" -Value `$aux }")
                :
                { ForEach-Object -Process $Process | Write-Output -NoEnumerate -OutVariable aux | ForEach-Object -Process {} -End { Set-Variable -Scope 1 $Variable -Value $aux } }
            } else {
              $isCommandPipeline ? 
                [scriptblock]::Create("$Process | Out-Null")
                : 
                { ForEach-Object -Process $Process | Out-Null }
            }
          ))
          $steppablePipeline = $steppableScriptBlock.GetSteppablePipeline($myInvocation.CommandOrigin)
          $steppablePipeline.Begin($PSCmdlet) 
        } 
        catch { $PSCmdlet.ThrowTerminatingError($_) }
      }
      process { try { $steppablePipeline.Process($InputObject) } catch { $PSCmdlet.ThrowTerminatingError($_) }; $InputObject }
      end     { try { $steppablePipeline.End() } catch { $PSCmdlet.ThrowTerminatingError($_) } }
      clean   { if ($null -ne $steppablePipeline) { $steppablePipeline.Clean() } }
    }
  11. dkaszews commented on Aug 18, 2023

    @dkaszews
    ContributorAuthor

    Any reason why you need [Parameter(ValueFromPipeline)] $InputObect? The typo clearly shows it's not used anywhere. Or is it just needed to enable piping into the function, even though we access those values via $_?

  12. mklement0 commented on Aug 18, 2023

    @mklement0
    Contributor

    Thanks for catching that, Dominik Kowalski (@dkaszews). You do need a ValueFromPipeline pipeline-binding parameter, and while its name doesn't matter if you use $_ in the process block instead, for clarity it's better to use the declared parameter there. I've fixed the code accordingly.

  13. dkaszews commented on Aug 18, 2023

    @dkaszews
    ContributorAuthor

    I played around trying to rebind the output pipe to either null, file or variable without converting the scriptblock to string and back, but no dice. { $Process | Out-Null } throws error in GetSteppablePipeline about it being empty (?), while { %{ $Process | Out-Null } } causes the $Process to never be invoked, probably one of ForEach-Object does not pass the $_ along.

    Maybe it is solveable with a smarter wrapper, maybe it is not possible without delving into engine internals. I poked around engine/lang/scriptblock.cs, it looks like there might be some way to sever or rebind the output pipe, but somebody more knowledgeable should chime in.

    For the testing, I used the following to distinguish the host and pipe output, it nicely shows whether the $Process is invoked and if so, whether it leaks.

    1..3 |
      Tee-WithProcess { %{ Write-Host 'Invoked'; 'Leaked' } } |
      ConvertTo-Json -Compress |
      Should -Be '[1,2,3]'
  14. jhoneill commented on Aug 19, 2023

    @jhoneill

    I played around trying to rebind the output pipe to either null, file or variable without converting the scriptblock to string and back, but no dice. { $Process | Out-Null } ....

    That's not going to work . At the very least it would to be { & $Process | Out-Null } to run the script block in the variable but that only seems to run as an END block ...

    The code I thought I originally posted

    function Invoke-Fork {
        param( 
            [Parameter(Position=0,Mandatory=$true)]  
            $ForkBlock,
            [Parameter(ValueFromPipeline=$true)]
            $InputObect 
        )
        begin   {try   {
                        $ForkBlock = [scriptblock]::Create( $forkBlock.ToString() + " | Out-Null" )
                        $steppablePipeline = $ForkBlock.GetSteppablePipeline($myInvocation.CommandOrigin)
                        $steppablePipeline.Begin($PSCmdlet) } 
                 catch {throw }
        }
        process {try   {$steppablePipeline.Process($_) ; Write-Output $_} catch {throw}}
        end     {try   {$steppablePipeline.End() } catch { throw }}
        clean   {if    ($steppablePipeline) { $null = $steppablePipeline.Clean() }  }
    }

    Passes your test but with the convert to/from string

    #553 [——€] PS7 ~> 1,2,3 | Invoke-Fork { %{ Write-Host 'Invoked'; 'Leaked' } } |   ConvertTo-Json -Compress  
    Invoked
    Invoked
    Invoked
    [1,2,3]
    

    I changed the begin block

                        #$ForkBlock = [scriptblock]::Create( $forkBlock.ToString() + " | Out-Null" )
                        $F2 = { Foreach-object -Process { & $ForkBlock | Out-Null}}
                        $steppablePipeline = $F2.GetSteppablePipeline($myInvocation.CommandOrigin)

    That works without the round-trip to string and back.

  15. 23 remaining items

  16. added
    Waiting on Author
    on Nov 28, 2023
  17. mklement0 commented on Nov 28, 2023

    @mklement0
    Contributor

    From my perspective, the proposal is as follows - I hope Dominik Kowalski (@dkaszews) and iRon7 agree:

    • Add a [scriptblock]-typed -Process parameter to Tee-Object.

    • Used in isolation, it allows you to quietly process the teed objects, such as by calling Export-Csv (success output, if any, should be discarded).

    • Used in combination with a teeing target (-Host, -Variable, -FilePath) it allows you to pre-process the teed objects: that is, it is the output from the script block that is sent to the target; e.g. -Process { Format-Table -GroupBy Foo } -Host

    • As for how to treat the -Process script block: The proposal is to infer from the AST of the script block whether it is:

      • a single command (pipeline) to which all teed objects can therefore be piped directly (via a steppable pipeline); e.g. -Process { Export-Csv out.csv }
      • otherwise, it is assumed to be per-input-object processing code - akin to the -ScriptBlock argument for ForEach-Object - that operates on $_, e.g. -Process { $_ + 1 }

    Examples and a proof-of-concept are in this comment.

    The open questions are:

    • Conceptual: Is the inference of the intended treatment of the -Process script block (too) obscure? Hopefully it'll "just work" from the user's perspective.

    • Technical:

      • Is there a way to use the given -Process script block as-is, without having to re-create it via its string representation / AST (which is what the proof-of-concept does), where context may be lost?
      • If not, is this an acceptable limitation (that will rarely be noticed in practice) that simply needs documenting?
  18. removed
    Waiting on Author
    on Nov 28, 2023
  19. iRon7 commented on Nov 29, 2023

    @iRon7

    Patrick Meinecke (@SeeminglyScience),

    a single command (pipeline) to which all teed objects can therefore be piped directly (via a steppable pipeline); e.g. -Process { Export-Csv out.csv }

    Just a thought: why not multiple?
    By dividing each pipeline to a hashtable item with a key equal to expanded scriptblock: "<scriptblock>".
    So that I can do things along with: -Process { Export-Csv E:\Test_csv\$($_.Appname).CSV }

  20. mklement0 commented on Nov 29, 2023

    @mklement0
    Contributor

    iRon7, I assume you mean supporting multiple script blocks, i.e. to type -Process as [scriptblock[]], right?

    That sounds like a nice enhancement, though we'd have to make it clear how that behaves in combination with a teeing target: if I understand you correctly, we'd then get:

    1..3 | Tee-Object -Process { Write-Output }, { $_ * 10 } -Host | Out-Null
    1
    10
    2
    20
    3
    30
  21. iRon7 commented on Nov 29, 2023

    @iRon7

    Michael Klement (@mklement0),

    I assume you mean supporting multiple script blocks, i.e. to type -Process

    No, what I meant is instead of a single pipeline, for each main process step check if the concerned pipeline is already started,
    If that is the case process it: $Pipeline["$ProcessScriptBlock"].Process($_)
    and if not, open a new pipeline:

    $Pipeline["$ProcessScriptBlock"] = $ProcessScriptBlock.GetSteppablePipeline()
    $Pipeline["$ProcessScriptBlock"].Begin()
    

    And at the end close all the $ProcessScriptBlock pipelines

    Basically as in these examples:

  22. iRon7 commented on Nov 29, 2023

    @iRon7

    Prototype of what I had in mind:

    function TeeObject {
        param([ScriptBlock]$Process)
        begin {
            $Pipeline = @{}
        }
        process {
            $Key = $ExecutionContext.InvokeCommand.ExpandString($Process.ToString())
            if (!$Pipeline.Contains($Key)) {
                $Pipeline[$Key] = $Process.GetSteppablePipeline()
                $Pipeline[$Key].Begin($True)
            }
            $Pipeline[$Key].Process($_)
            $_	# pass on the current item
        }
        end {
            $Pipeline.get_Values().End()
        }
    }
    
    $Csv = @'
    name,  account,  Appname, count, users, List
    name1, account1,     123,     1,     2, abc
    name1, account2,     123,     2,     3, z
    name1, account3,     123,     3,     6, xc
    name1, account4,     123,     5,     7, df
    name1, account5,     123,     5,     8, rg
    name1, account6,     123,     7,     0, sfg
    name2, account1,     456,     1,     1, dfg
    name3, account1,     789,     3,     7, rt
    name3, account2,     789,     7,     1, ert
    '@
    
    $Csv | ConvertFrom-Csv | TeeObject -Process { Export-Csv .\$($_.Appname).Csv } | Out-Null
  23. mklement0 commented on Nov 29, 2023

    @mklement0
    Contributor

    iRon7, while I can see the appeal of such functionality in principle, I don't think the implementation you're proposing is the way to go (and I'm not sure there is an alternative way that fits into this proposal, which doesn't preclude thinking about it separately, however):

    • The behavior is obscure and may situationally not be desired.
    • More importantly, given that string interpolation evaluates arbitrary subexpressions ($(...)), their repeated evaluation may be undesired, not just for performance reasons, but because those expressions may have side effects, potentially even destructive ones if repeated.
  24. removed
    Needs-Triage
    on Nov 30, 2023
  25. SeeminglyScience commented on Nov 30, 2023

    @SeeminglyScience
    Contributor

    (misclick fyi)

  26. mklement0 commented on May 13, 2024

    @mklement0
    Contributor

    rhubarb-geek-nz, that's an interesting cmdlet, but it serves a different use case: sending a single pipeline's input to multiple, independent script blocks for output-less processing.

    Here, we are talking about extension to Tee-Object, whose core mandate is to pass its pipeline input through, while allowing one additional target to also pass the input to.
    (#20123 (comment) toyed with the idea of supporting multiple, -Process script blocks, but it was based on a misreading of iRon7's intent, and I'm not convinced it is necessary.)

  27. groutoutlook commented on Aug 25, 2025

    @groutoutlook

    Hi, is this issue abandoned? Hope team could recognize how convenient this feature will help for daily scripting need of every developers in a Windows box like me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-EnhancementWG-EngineWG-NeedsReview

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions