Tee-Object

Using Tee-Object in PowerShell: Capture and Continue the Pipeline

Welcome back to Wahmans Powershell Blog! Today, we’re diving into a really handy and sometimes overlooked cmdlet: Tee-Object. According to the official Microsoft Docs, Tee-Object “Saves command output in a file or variable and also sends it down the pipeline.” What does that mean in practice? Let’s break it down with some examples, moving from beginner-friendly to more advanced use cases.

What is Tee-Object?

Tee-Object allows you to capture the output of a command and simultaneously send that output further down the pipeline. This is incredibly useful when you want to save data for logging or debugging while still continuing to manipulate that data.


Example 1: Save Output to a File (Beginner)

Let’s say you’re listing all services on your system and want to save them to a file, while also being able to display them in your console.

Get-Service | Tee-Object -FilePath "C:\Temp\services.txt"

This command will display the services in your console AND save them to C:\Temp\services.txt.


Example 2: Save Output to a Variable and Use It (Intermediate)

If you’re running a command and want to reuse its output later in a script, use Tee-Object with -Variable:

$services = Get-Service | Tee-Object -Variable svc 
$svc | Where-Object { $_.Status -eq 'Running' }

The first line stores the output of Get-Service in a variable called svc, which is then used in the next command.


Example 3: Logging While Processing (Advanced)

Let’s say you’re processing a list of events and you want to log raw event data for future auditing, while still continuing analysis in your script:

Get-EventLog -LogName Application -Newest 100 | 
    Tee-Object -FilePath "C:\logs\app_events.log" | 
    Where-Object { $_.EntryType -eq 'Error' }

Here, the raw event data is logged to a file, but errors are filtered further down the pipeline.


Example 4: Splitting Output for Multi-Destination Processing (Advanced)

Imagine you’re building an automation script and want to send data to a log, update a dashboard, and filter it:

$services = Get-Service | 
    Tee-Object -FilePath "C:\Temp\allservices.log" | 
    Tee-Object -Variable allServices | 
    Where-Object { $_.Status -eq 'Running' } 

# Save results to JSON for dashboard
$services | ConvertTo-Json | Out-File "C:\Temp\running_services.json"

This script does a lot in one go—logs everything, extracts running services, and produces a dashboard-friendly JSON output.


Final Thoughts

Tee-Object is excellent for scenarios where you need to inspect or preserve output without sacrificing pipeline flow efficiency. Whether for debugging, logging, or splitting outputs, it’s a great tool to have in your scripting arsenal.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *