Powershell piping to variable and write-host at the same time

Razorx picture Razorx · May 27, 2015 · Viewed 7.3k times · Source

Hello all and thanks for your time in advance;

I'm running into a slight issue.

I'm running a command and piping it into a variable so i can manipulate the output.

$variable = some command

this normally works fine but doesn't output what's happening to the screen, which is fine most of the time. However occasionally this command requires some user input (like yes or no or skip for example), and since it's not actually piping anything to the command window, it just sits there hanging instead of prompting the user. If you know what to expect you can hit y or n or s and it'll proceed normally.

Is there anyway to run the command so that the output is piped to a variable AND appears on screen? I've already tried:

($variable = some command) 

I've also tried:

write-host ($variable = some command) 

But neither work. Note that the command running isn't a native windows or shell command and I cannot just run it twice in a row.

To clarify (because i probably wasn't clear)

I've also tried :

$variable = some command : Out-host

and

$variable = some command | out-default

with all their parameters, But the "prompt" from the command (to write y, n, s) doesn't show up.

Being able to pass S automatically would also be acceptable.

Answer

TheMadTechnician picture TheMadTechnician · May 27, 2015

Sounds like you need Tee-Object. Example:

some command | Tee-Object -Variable MyVariable

This should pass everything from the command down the pipe, as well as store all output from the command in the $MyVariable variable for you.