Mohammad Hossein Amri
Mohammad Hossein Amri

Reputation: 1985

Use Tee-Object with redirecting

I want to run this command and redirect all the output to Windows as well as a log file.

powershell "C:\backup\backup.bat *>&1 | tee log.txt"

so when I run the command I can see the output and also save it in a file, but I am getting this error:

Ampersand not allowed. The & operator is reserved for future use; use "&" to pa
ss ampersand as a string.
At line:1 char:25
+ C:\backup\backup.bat *>& <<<< 1 | tee log.txt
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : AmpersandNotAllowed

Upvotes: 4

Views: 9028

Answers (2)

Mikhail Tumashenko
Mikhail Tumashenko

Reputation: 1723

To get the output of .bat file execution to the console as well as to file, use:

powershell "& 'C:\backup\backup.bat' *>&1  | Tee-Object -FilePath 'log.txt'"

There's a good post, PowerShell and external commands done right, which explains how to start external command. After that simply apply redirection as in the article you linked.

Upvotes: 8

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Redirection of streams other than Success and Error (AKA STDOUT and STDERR) isn't supported prior to PowerShell v3, as @CB. mentioned in comments. In PowerShell v2 you can only merge the Error stream:

powershell "C:\backup\backup.bat 2>&1 | tee log.txt"

Upvotes: 4

Related Questions