如何将批处理脚本的输出打印到文件中,而不影响它在脚本上的显示方式

时间:2016-03-11 21:19:09

标签: windows batch-file

我有一个打印大量信息的脚本,但也需要用户输入。

我需要能够在命令窗口中看到显示,但还要将屏幕上的输出打印到日志文件中。

-------------------------------
Info Here
-------------------------------
What is your favorite color? Blue

You sad your favorite color is "Blue".
Executing: AttackByBunny.exe

我更喜欢可以设置在最顶端的方式并适用于以下所有内容。

SET ECHO OFF
SET FILEOUTPUT FILE.log
exec monty.exe

尝试w / jtee.bat更新:
这似乎不适用于下面的脚本。 它只是退出call mvn ...行。 暂停仅用于调试目的。

更新的脚本:

@echo off
set RELEASE_BRANCH=PROD_Release_7_0
echo Using NON_PROD_ENV/%RELEASE_BRANCH% | jtee.bat %RELEASE_BRANCH%.log
pause
if exist %RELEASE_BRANCH% (
    echo Running svn update %RELEASE_BRANCH% | jtee.bat %RELEASE_BRANCH%.log 1
    svn update %RELEASE_BRANCH% | jtee.bat %RELEASE_BRANCH%.log 1
) else (
    echo Running svn co https://svn_rep/branches/releases/NON_PROD_ENV/%RELEASE_BRANCH% | jtee.bat %RELEASE_BRANCH%.log 1
    svn co https://svn_rep/branches/releases/NON_PROD_ENV/%RELEASE_BRANCH% | jtee.bat %RELEASE_BRANCH%.log 1
)
pause
cd %RELEASE_BRANCH%
pause
call mvn clean release:clean release:prepare -DpreparationGoals="install" -DcompletionGoals="install versions:use-next-snapshots versions:commit" -Darguments='-Dmaven.test.skip=true' | jtee.bat ../%RELEASE_BRANCH%.log 1

pause

2 个答案:

答案 0 :(得分:1)

以下是我在上面的评论中提到的.NET方法的完整说明。这是一个批处理+ PowerShell混合脚本(使用.bat扩展名保存),它将控制台窗口的缓冲区内容保存到名为“buffer.log”的文件中。

<# : Batch portion (PowerShell multi-line comment)
@echo off & setlocal

call :saveBuffer buffer.log
goto :EOF

:saveBuffer <outputfile>
set "logfile=%~f1"
powershell -noprofile -noninteractive "iex (${%~f0} | out-string)"
goto :EOF

: end batch / begin PowerShell hybrid chimera #>
$w = $Host.UI.RawUI.WindowSize.Width - 1
$h = $Host.UI.RawUI.CursorPosition.Y - 1
$rect = New-Object Management.Automation.Host.Rectangle 0, 0, $w, $h
$buffer = $Host.UI.RawUI.GetBufferContents($rect)
$lineBuilder = New-Object System.Text.StringBuilder
$out = New-Object System.Text.StringBuilder

# for older .NET compatibility
if (-not $lineBuilder.Clear) {
    $lineBuilder | Add-Member ScriptMethod Clear {$this.Length = 0}
}

foreach ($byte in $buffer) {
    [void]$lineBuilder.Append($byte.character)
    if (-not (++$x % ($w + 1))) {
        # End of line reached.  Append right-trimmed line to $out and start a new line.
        [void]$out.AppendLine($lineBuilder.ToString().TrimEnd())
        [void]$lineBuilder.Clear()
    }
}

# Write log file.  For UTF8, change encoding to utf8
$out.ToString() | out-file $env:logfile -encoding Default -width $w -force

答案 1 :(得分:1)

Here you can find tee command for windows without external binaries。 如果您调用文件jtee.bat,则可以使用它:

someCommand.exe arguments | jtee.bat FILE.log 1

最后的1表示如果文件已经存在,脚本会附加日志。