How to use the command Tee-Object (with examples)
The Tee-Object command in PowerShell is used to save command output in a file or variable and also send it down the pipeline. It is a powerful tool for logging or storing command output while still being able to interact with the data in subsequent pipeline stages.
Use case 1: Output processes to a file and to the console
Code:
Get-Process | Tee-Object -FilePath path\to\file
Motivation: In certain scenarios, it is necessary to capture the output of a command and store it in a file for future reference, but at the same time, it is also important to see the output on the console in real-time. The Tee-Object command provides a convenient way to achieve this.
Explanation:
Get-Process
retrieves a list of all running processes on the system.Tee-Object
takes the output of the previous command and saves it to the specified file path using the-FilePath
parameter. It also passes the output down the pipeline.path\to\file
is the file path where the command output will be saved. You should replace it with the actual file path.
Example output: The command will display the list of running processes on the console and also save the same output to the specified file. This allows you to monitor the progress on the console while having a permanent record in the file.
Use case 2: Output processes to a variable and Select-Object
Code:
Get-Process notepad | Tee-Object -Variable proc | Select-Object processname, handles
Motivation: Sometimes, it is necessary to capture the output of a command and store it in a variable for further processing or analysis. The Tee-Object command can be used to simultaneously save the output to a variable and continue working with it in subsequent pipeline stages.
Explanation:
Get-Process notepad
retrieves information about the notepad processes running on the system.Tee-Object
takes the output of the previous command and saves it to the specified variable using the-Variable
parameter. It also passes the output down the pipeline.proc
is the name of the variable where the command output will be stored. You can choose any valid variable name.
Example output:
The command will display the process name and handles of the notepad processes on the console. It will also store the same output in the proc
variable. This allows you to access and manipulate the process information in subsequent pipeline stages, such as filtering or sorting the data.
Conclusion:
The Tee-Object command in PowerShell is a useful tool for capturing command output and simultaneously saving it to a file or variable. It enables you to have a permanent record of the output for future reference, while still being able to interact with the data in subsequent pipeline stages. Whether you need to log output to a file or store it in a variable for further processing, Tee-Object provides a flexible solution.