skip to Main Content

Tee-Object and Invoke-Expression in PowerShell

The PowerShell Tee-Object Cmdlet allows you to send command output to a file or a variable, and display it in the console at the same time. This is very useful for those instances where you need to parse the text output of a command. I had a hard time getting it to work with Invoke-Expression. After trying different things, I finally found the solution. To get Tee-Object to work with Invoke-Expression in PowerShell 1, include the Tee command in the Invoke-Expression command like this:

Invoke-Expression "mvn clean install | Tee –variable result”

The following, which I guess is what most people try first, doesn’t work (at least in PowerShell V1). I guess because you are storing the result of the “Invoke-Expression” command itself into the variable instead of “mvn clean install”.

    Invoke-Expression "mvn clean install” | Tee -variable result

Wrapping Invoke-Expression in parenthesis (see below) works, but has a drawback: the output is not written to Standard Out until the whole command finishes.

    (Invoke-Expression "mvn clean install”) | Tee -variable result

I occasionally blog about programming (.NET, Node.js, Java, PowerShell, React, Angular, JavaScript, etc), gadgets, etc. Follow me on Twitter for tips on those same topics. You can also find me on GitHub.

See About for more info.

This Post Has 6 Comments

Leave a Reply

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

Back To Top