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 a Microsoft MVP and an IT veteran with almost 20 years of experience, much of it spent as an IT consultant specializing in Windows server technologies. He works today as an independent author, trainer and consultant. His latest book is Managing Active Directory with Windows PowerShell 2.0: TFM (SAPIEN Press 2011). Follow Jeff on Twitter and on his blog.

Reader Comments:

Add Your Comment Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above