CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Tee-Object cmdlet – Redirect output to two directions

When we use commands at the PowerShell prompt, the commands display the output on the console. When we use the pipe symbol, the output will be redirected to another command. Through this Article, I will explain how to redirect the output to a file, using Tee-Object cmdlet.

Tee-Object cmdlet

Tee-Object cmdlet is a useful command in PowerShell that redirects the output in two directions. This command will save the output to a file and also redirect the output to the pipeline or display on the console.

To send the output to the file, we need to use the -FilePath parameter and also provide the complete path of the filename. For example, the below command displays the list of entries in the directory and also saves the output to a file.

PS C:\> Get-ChildItem | Tee-Object -FilePath "C:\tee.txt"

This command allows appending the output to the file using the -Append parameter. The below command appends the output (list of processes) to the file “C:\tee.txt” which already contains the list of directory entries.

PS C:\> Get-Process | Tee-Object -FilePath "C:\tee.txt" -Append

Tee-Object cmdlet also saves the output to a variable. You need to pass the variable name through its parameter -Variable. The below command displays the list of services and also saves the list to a variable “var”.

PS C:\> Get-Process | Tee-Object -Variable var

To display the content of the variable “var“, you can type the variable name with the dollar sign (“$”) at the PowerShell prompt.

PS C:\> $var

Note that, variables in PowerShell start with a dollar (“$”) sign. But when you give the variable through the -Variable parameter you need to give the variable name without a dollar sign (“$”); otherwise, PowerShell throws the below Error.

PS C:\> Get-Process | Tee-Object -Variable $var
Tee-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Variable'. Specified method is not supported.
At line:1 char:36
+ Get-Process | Tee-Object -Variable $var
+                                    ~~~~
    + CategoryInfo          : InvalidArgument: (:) [Tee-Object], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.TeeObjectCommand

We will discuss more topics as we go.

See also, “PowerShell – How to create files and folders?.

[..] David

PowerShell – Tee-Object cmdlet – Redirect output to two directions

One thought on “PowerShell – Tee-Object cmdlet – Redirect output to two directions

Leave a Reply

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

Scroll to top