Tee-Object cmdlet

How often do you use the Tee-Object cmdlet?  If you are anything like me I would guess fairly infrequently – if at all.  It does deserve to be considered.

Think of running  Get-Process.  We get a nice display on screen. We may decide to save the output

Get-Process | Out-File c:\test\proc1.txt

but now we don’t see the output.  Its in the file so we can look at it

Get-Content c:\test\proc1.txt

but that now becomes a two step process.

 

Tee-Object supplies the answer because it functions as a “T” junction and effectively splits the data

Get-Process | Tee-Object -FilePath c:\test\proc2.txt

gives us a display on screen (because Tee-Object ends the pipeline) and a file output – test with Get-Content c:\test\proc2.txt

We can add further processing after the Tee

Get-Process | Tee-Object -FilePath c:\test\proc2.txt | where {$_.Name -like "p*"} | Format-Table

 

Instead of a file we can tee to a variable

Get-Process | Tee-Object -Variable procs

Notice that we don’t use a $ in front of the variable name!!

$procs

will display the data again

If we look at the type of the data

$procs | gm

We see that its TypeName: System.Diagnostics.Process which means we can perform all our usual PowerShell processing e.g.

 

Unfortunately there isn’t a way to append data to file with Tee-Object  but it does have a very practical purpose and deserves a bit more attention.

6 Responses to Tee-Object cmdlet

  • Mike Shepard says:

    Nice article. I’m in the same boat that I don’t seem to use tee-object very often. Thanks for reminding me of some of its uses.

  • RichardSiddaway says:

    Pleasure. Glad you found it useful.

  • potatohead5280 says:

    I LOVE t-object…use it all the time. I hadn’t thought of piping to a variable though – that’s a great idea!

  • Klaus Salger says:

    I find Tee quite usefull for logging. Hope MS will add an append parameter or the like in a future release.
    Meanwhile I’m using something like this to pipe messages to the screen and a logfile:
    Tee-Object -Variable LastMessage; $LastMessage >> $logfile

  • martind says:

    Tee-Object without the append parameter is useless for logging. I use a similar function as the one below as a workaround. Hopefully Microsoft will add it someday.

    function myTee-Object ($text,$file) {Write-Host $text ; Write-Output $text | Out-File $file -Append}

    myTee-Object “sometexthere” c:\test.txt

  • RichardSiddaway says:

    Tee-Object is not designed for logging. If you want to perform logging put as a distinct call in your processing

Leave a Reply