How can I redirect output to a text file and the console (cmd) window at the same time?
4 Answers
Powershell 2.0 comes with the Tee-Object
cmdlet which does exactly that. If you're using Windows 7, it comes with Powershell 2.0 installed. If you're using an older version of Windows, Powershell 2.0 is available for download.
The benefit of Powershell is that it can run the commands that cmd can as well.
Example:
dir | Tee-Object -file c:\output\dir.txt
There's a good answer for an identical question on StackOverflow
In summary, find a Win32 port of the Unix tee
command.
I have made a batch file tool for this:
@ECHO OFF
SETLOCAL
SET Append=false
IF /I "%~1]=="/a" ( SET Append=true & SHIFT )
IF "%~1"== "" GOTO help
IF "%~2"== "" GOTO help
SET Counter=0
FOR /F %%A IN ('DIR /A /B %1 2^>NUL') DO CALL :Count "%%~fA"
IF %Counter% GTR 1 ( SET Counter= & GOTO Syntax )
SET File=%1
DIR /AD %File% >NUL 2>NUL
IF NOT ERRORLEVEL 1 ( SET File= & GOTO Syntax )
SET Y=
VER | FIND "Windows NT" > NUL
IF ERRORLEVEL 1 SET Y=/Y
IF %Append%==false (COPY %Y% NUL %File% > NUL 2>&1)
FOR /F "tokens=1* delims=]" %%A IN ('FIND /N /V ""') DO (
> CON ECHO.%%B
>> %File% ECHO.%%B
)
ENDLOCAL
GOTO:EOF
:Count
SET /A Counter += 1
SET File=%1
GOTO:EOF
:help
ECHO.
ECHO Display text on screen and redirect it to a file simultaneously ECHO Usage: some_command ^| TEE.BAT [ /a ] filename
ECHO.
ECHO Where: "some_command" is the command whose output should be redirected
ECHO "filename" is the file the output should be redirected to
ECHO /a appends the output of the command to the file,
ECHO rather than overwriting the file
ECHO.
ECHO Made by Wasif Hasan. Nov 2019
Usage: command | tee
Usage:
command | tee [/a] filename
[
/a
] will append to the file instead of over writing.
Use Tee-Object to pipe to variable with the -variable switch then use the variable to output to screen how you would like
get-aduser -filter * -Properties Name, CanonicalName, LogonWorkstations | where { $_.logonworkstations -match "\D" } | Select Name, CanonicalName, logonworkstations | sort canonicalname | Tee-Object -variable Users | Export-Csv -Path ".\$($MyInvocation.MyCommand.Name.split(".")[0])__$(Get-Date -uformat "%Y-%m-%d_%I-%M-%S_%p").csv" -NoTypeInformation
$Users | FL
Clear-Variable Users
-
1Welcome. This question is about the Command Prompt (CMD) not PowerShell. Commented Sep 6, 2019 at 21:32