Photo by Alex Read on Unsplash

Tee-Object  is one of those PowerShell cmdlets that’s always been there but rarely used. I can count on two hands in my nearly 10 years of PowerShell development work that I’ve needed or even thought to use this cmdlet but when I do, it works great!

Using Tee-Object with a File

What does Tee-Object  do anyway? Tee-Object basically kills two birds with one stone. This cmdlet redirects output from a PowerShell command and either saves it to a file or to a variable while also returning the output to the pipeline. It allows a scripter to save the output and send the output across the pipeline all in one shot.

Let’s say a scripter wants to send some text to a file and then perform kind of task on that same text afterward. Perhaps we’re pulling a list of Windows services from a computer and saving that output to a text file to create a snapshot of the before state before we attempt to start the services. This task can be done in two separate steps or with a single one with Tee-Object .

Without Tee-Object , this task may look something like this:

Ready to stop reading and start learning about PowerShell, DSC, Windows Server, Sharepoint, IIS and dozens of other categories? If so, check out the hundreds of free technical demo screencasts available on the new, IT career development platform TechSnips.

This method works but there’s a better way with Tee-Object . The Tee-Object  cmdlet has a FilePath  parameter we can use to save the output to a file. Here’s what this same task would look like with Tee-Object . Notice how we’re using the pipeline to transfer the objects from one command to the next.

This method always replaces the text in a file. If we would have rathered appended the text in the file, we could have used the Append  switch parameter.

Using Tee-Object with a Variable

The Tee-Object  PowerShell cmdlet also has a variable parameter that, instead of sending output to a file, it sends the output to a variable. Instead of first assigning the output of Get-Service  to the variable $servciceStatusBefore , we can simply use the Variable parameter on Tee-Object to create the variable and send the output there. Then, since Tee-Object always returns the input it receives back to the pipeline, we can use that as input to Start-Service as we did in the above example.

Wrap up

Tee-Object is one of those PowerShell commands that aren’t necessarily required in your PowerShell code but make it cleaner and less dense. Using Tee-Object allows a scripter to cut down on the number of lines of code yet performs exactly the same task. Granted, eliminating code does sometimes make the code a little less readable but that’s up to the scripter to decide on that tradeoff!

Whenever you need to either save command output to a file or to a variable, take a look at the Tee-Object cmdlet.

%d bloggers like this: