![如何将输出同时重定向到文本文件和控制台(cmd)窗口?](https://linux22.com/image/1231129/%E5%A6%82%E4%BD%95%E5%B0%86%E8%BE%93%E5%87%BA%E5%90%8C%E6%97%B6%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%E5%92%8C%E6%8E%A7%E5%88%B6%E5%8F%B0%EF%BC%88cmd%EF%BC%89%E7%AA%97%E5%8F%A3%EF%BC%9F.png)
如何将输出同时重定向到文本文件和控制台(cmd)窗口?
答案1
Powershell 2.0 附带Tee-Object
cmdlet 就是这样做的。如果您使用的是 Windows 7,它附带安装了 Powershell 2.0。如果您使用的是旧版本的 Windows,Powershell 2.0 是可供下载。
Powershell的好处是它也可以运行cmd可以运行的命令。
例子:
dir | Tee-Object -file c:\output\dir.txt
答案2
答案3
我为此制作了一个批处理文件工具:
@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
用法:
command | tee [/a] filename
[
/a
] 将附加到文件而不是覆盖。
答案4
使用 Tee-Object 通过 -variable 开关将变量传输到管道,然后使用变量按照您的需要输出到屏幕
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