Prof. Powershell

Suits Me to a Tee

The Tee-Object cmdlet offers up another way of seeing data coughed up by other output cmdlets.

When you run a command in PowerShell, the output is written to the console:

PS C:\ get-service

Simple enough. If you want to save the results to a text file, I recommend using the Out-File cmdlet and not the legacy console redirection characters of > and >>:

You have to be careful here as what you see on the screen is exactly what gets saved to the text file. If the output is truncated on the screen it will be truncated in the file. I’ll show you other ways to handle this another time.

But what if you want to see the results and save them to a file? For that we’ll use the Tee-Object cmdlet, which has an alias of Tee:

PS C:\> ps | where {$_.workingset -gt 5mb} | sort workingset -desc | tee data.txt

Smashing. This has some other interesting applications because Tee-Object keeps sending the original objects down the pipeline. Thus, I can have an expression like this:

PS C:\> ps | where {$_.workingset -gt 5mb} | sort workingset -desc | tee data.txt | measure-object workingset -sum

Count    : 11
Average  :
Sum      : 355483648
Maximum  :
Minimum  :
Property : WorkingSet

I won't see the output from Get-Process as I did before. The original process objects are passed to Measure-Object which writes a different object to the pipeline, but the results will still be saved to the text file.

You can also use Tee to save objects to a variable instead of a file. Use the –variable parameter:

PS C:\> ps | where {$_.workingset -gt 5mb} | sort workingset -desc | tee -variable procs | export-clixml procdata.xml
PS C:\> $procs.count
11
PS C:\> (import-clixml procdata.xml).count
11

My main point here is to demonstrate that it's all the same data that can be used, in essence, simultaneously. As always, don't forget to take a moment and look at help for Tee-Object.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

Upcoming Training Events

0 AM
Live! 360 Orlando
November 17-22, 2024
TechMentor @ Microsoft HQ
August 11-15, 2025