Repository navigation
Open
Labels
Issue-Enhancementthe issue is more of a feature request than a bugWG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group
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:
Tee-Objectshould have a-Consoleparameter #19827 -... | Tee-Object -Host | ...could be written as... | Tee-Object -Process { Write-Host } | ...(bit verbose, soTee-Objectshould have a-Consoleparameter #19827 on its own is probably still a good idea)-PassThruas common parameter #19989 -... | ExportCsv files.csv -PassThru | ...could be written as... | Tee-Object -Process { Export-Csv files.csv } | ...(saves on adding-PassThruto each missing cmdlet- On top of
#19989, add-Formatparameter toWrite-Host#20121 -... | Write-Host -PassThru -Format "Processing: $_" | ...could be written as... | Tee-Object -Process { Write-Host "Processing: $_" }
Proposed technical implementation details (optional)
Opens:
- 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 asForEach-Item { $_ | $Process; $_ }:> 0..4 | ConvertTo-Json [ 0, 1, 2, 3, 4 ] > 0..4 | %{ ConvertTo-Json } 0 1 2 3 4
- 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. - 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 with0..4 | %{ $_; $_ } | Measure-Objectoutputting10. - 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?
- 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$_inTee-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 forForEach-Object.
Reacted by Michael Klement, iRon7 and Travis LaGrone
Metadata
Metadata
Assignees
Labels
Issue-Enhancementthe issue is more of a feature request than a bugWG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group
Activity
jhoneill commentedon Aug 17, 2023
YES
{ $_ | Export-Csv files.csv }and{ $_} | Export-Csv files.csvare 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 thatexport-csvin 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 oneI'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 :-)
So this works
and the block can be a multi-command pipeline
My addition of
| out-nullworksWrite-host works - what gets printed when is harder to follow.
Roughly what you're looking to do ?
dkaszews commentedon Aug 18, 2023
James O'Neill (@jhoneill) Will have to play around it, but this looks amazing 🤩
mklement0 commentedon Aug 18, 2023
A steppable pipeline looks promising, but note that
Invoke-Forkdoesn'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.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:
Export-Csv) ...-Variableor-FilePathare also specified, in which case capture the output in the specified variable or save it to the specified file.-Hostswitch (seeTee-Objectshould have a-Consoleparameter #19827), print directly to the host (display).dkaszews commentedon Aug 18, 2023
Michael Klement (@mklement0) How is
Measure-Commandimplemented? Because I noticed that one does silence all output unless you explicitly pipe the measured command intoOut-Default.mklement0 commentedon Aug 18, 2023
Good question, Dominik Kowalski (@dkaszews).
It uses the
internal.InvokeWithPipe()method directly on the inputScriptBlock(-Expressionargument), and uses a null pipe as the output (new Pipe { NullPipe = true }):PowerShell/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs
Lines 62 to 69 in 14bd9c7
Note that the script block is invoked for every input object, with
$_bound to that object, as the following example demonstrates:dkaszews commentedon Aug 18, 2023
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
teeand process substitution. I wonder whether a better idea would be to portmkfifoand allow to do this kind of plumbing directly in PowerShell.Edit: sorry, I missed the last part. So the
Measure-Commanddoes not support streaming objects, which is the issue I mentioned in open 1., might be a dead end then.mklement0 commentedon Aug 18, 2023
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.
jhoneill commentedon Aug 18, 2023
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.
mklement0 commentedon Aug 18, 2023
Good point -
Out-Nullcan be integrated into the pipeline in the steppable script block, and the-FilePathand-Variablecases 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
-Variablecase sets the output variable viaSet-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:
Tee-WithProcesssource code:dkaszews commentedon Aug 18, 2023
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$_?mklement0 commentedon Aug 18, 2023
Thanks for catching that, Dominik Kowalski (@dkaszews). You do need a
ValueFromPipelinepipeline-binding parameter, and while its name doesn't matter if you use$_in theprocessblock instead, for clarity it's better to use the declared parameter there. I've fixed the code accordingly.dkaszews commentedon Aug 18, 2023
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 inGetSteppablePipelineabout it being empty (?), while{ %{ $Process | Out-Null } }causes the$Processto never be invoked, probably one ofForEach-Objectdoes 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
$Processis invoked and if so, whether it leaks.jhoneill commentedon Aug 19, 2023
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
Passes your test but with the convert to/from string
I changed the begin block
That works without the round-trip to string and back.
23 remaining items
mklement0 commentedon Nov 28, 2023
From my perspective, the proposal is as follows - I hope Dominik Kowalski (@dkaszews) and iRon7 agree:
Add a
[scriptblock]-typed-Processparameter toTee-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 } -HostAs for how to treat the
-Processscript block: The proposal is to infer from the AST of the script block whether it is:-Process { Export-Csv out.csv }-ScriptBlockargument forForEach-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
-Processscript block (too) obscure? Hopefully it'll "just work" from the user's perspective.Technical:
-Processscript 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?iRon7 commentedon Nov 29, 2023
Patrick Meinecke (@SeeminglyScience),
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 }mklement0 commentedon Nov 29, 2023
iRon7, I assume you mean supporting multiple script blocks, i.e. to type
-Processas[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:
iRon7 commentedon Nov 29, 2023
Michael Klement (@mklement0),
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:
And at the end close all the
$ProcessScriptBlockpipelinesBasically as in these examples:
iRon7 commentedon Nov 29, 2023
Prototype of what I had in mind:
mklement0 commentedon Nov 29, 2023
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):
$(...)), 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.SeeminglyScience commentedon Nov 30, 2023
(misclick fyi)
mklement0 commentedon May 13, 2024
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,
-Processscript blocks, but it was based on a misreading of iRon7's intent, and I'm not convinced it is necessary.)groutoutlook commentedon Aug 25, 2025
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.