Prof. Powershell

Tee Off

Tee-Object -- a slight variation on the Out-File cmdlet.

Last time I showed you how to use Out-File to redirect output to a text file. One downside to this cmdlet is that you can't see the expression output until you open the text file. Wouldn't it be nice to see the command result and still save them to a text file? In PowerShell we use the Tee-Object cmdlet, which has an alias of Tee:

PS C:\> get-service | where {$_.status -ne "Running"} | Tee NotRunning.txt

When you run this command, PowerShell will display the results to the console and save them to the text file NotRunning.txt.

The Tee-Object cmdlet does not have the same parameters as Out-File, so you can't have the output be appended or prevent a previous file from being overwritten. You also can't specify the encoding type. However, you can use an input object as in these two examples:

PS C:\> $p = get-process

PS C:\> tee myprocs.txt -input $p

Remember that $p is a collection of process objects. The objects are formatted before being written to the text file, myprocs.txt. But because $p is an object, we could use expressions like these:

PS C:\> tee topten.txt -input ($p | sort cpu -desc | select -first 10)

PS C:\> tee proc.txt -input $p[0..4]

The first example sorts the contents of $p by CPU in descending order and then selects the first 10 processes. The second example simply outputs the first 5 processes in $p.

If you've been using PowerShell for a little bit, you will realize these expressions could also be written like these ones:

PS C:\> $p | sort cpu -desc | select -first 10 | tee topten.txt

PS C:\> $p[0..4] | tee proc.txt

The net result is the same in either. Which format to use will depend on your PowerShell needs at the time. I expect you'll more often use the latter format, but I wouldn't rule out a complex script or function where the first example would be easier to use.

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