如何在Windows中随时从命令提示符捕获显示输出?

c7rzv4ha  于 8个月前  发布在  Windows
关注(0)|答案(6)|浏览(143)

我特灵捕捉德信息显示在命令提示符(命令窗口)在特定的时刻,并将其发送到一个文本文件。
我有一个用C/C++编写的应用程序,它是通过这样的批处理脚本启动的:

c:\myProgramInC.exe
echo "Ending with error"
PAUSE

myProgramInC.exe总是在运行(有一个无限循环),所以如果我的脚本到达echo命令,这意味着我的应用程序以abend结束。
我想得到的是脚本结束执行之前的前几行,因为我的myProgramInC.exe总是打印关于发生了什么的信息,并且当错误发生时,查看它发生了什么是非常有用的。这样的事情

c:\myProgramInC.exe
**** Execution of process to get te previous N lines in the command prompt ****
echo "Ending with error"
PAUSE

我知道cmd窗口有一个缓冲区,我一直在考虑从这样的缓冲区捕获所有这些数据。它是任何方法来获得此信息作为文本存储在一个文件?
我一直在尝试一些更专业的东西,比如用ProcDump转储内存,但由于我同时运行各种myProgramInC.exe(每个都存储在不同的位置),我只是得到消息“多个进程与指定的名称匹配”。其余的选项对我来说没有用,因为我的应用程序没有响应,它只是结束了。
有什么想法吗?

ht4b089n

ht4b089n1#

好吧,可能有一个更优雅的方法来做到这一点,但这将工作假设你有PowerShell。
创建一个名为Get-ConsoleAsText.ps1的PowerShell脚本文件,其中包含以下脚本。注意,我没有创建此脚本。我在Windows PowerShell Blog - Capture console screen找到的。

#################################################################################################################
# Get-ConsoleAsText.ps1
#
# The script captures console screen buffer up to the current cursor position and returns it in plain text format.
#
# Returns: ASCII-encoded string.
#
# Example:
#
# $textFileName = "$env:temp\ConsoleBuffer.txt"
# .\Get-ConsoleAsText | out-file $textFileName -encoding ascii
# $null = [System.Diagnostics.Process]::Start("$textFileName")
#

# Check the host name and exit if the host is not the Windows PowerShell console host.
if ($host.Name -ne 'ConsoleHost')
{
  write-host -ForegroundColor Red "This script runs only in the console host. You cannot run this script in $($host.Name)."
  exit -1
}

# Initialize string builder.
$textBuilder = new-object system.text.stringbuilder

# Grab the console screen buffer contents using the Host console API.
$bufferWidth = $host.ui.rawui.BufferSize.Width
$bufferHeight = $host.ui.rawui.CursorPosition.Y
$rec = new-object System.Management.Automation.Host.Rectangle 0, 0, ($bufferWidth), $bufferHeight
$buffer = $host.ui.rawui.GetBufferContents($rec)

# Iterate through the lines in the console buffer.
for($i = 0; $i -lt $bufferHeight; $i++)
{
  for($j = 0; $j -lt $bufferWidth; $j++)
  {
    $cell = $buffer[$i, $j]
    $null = $textBuilder.Append($cell.Character)
  }
  $null = $textBuilder.Append("`r`n")
}

return $textBuilder.ToString()

如果您单独调用PowerShell脚本,它将读取控制台缓冲区并将其写回屏幕

PowerShell -noprofile -sta -command "C:\Scripts\Get-ConsoleAsText.ps1"

你也可以像这样调用它来捕获文件的内容:

PowerShell -noprofile -sta -command "C:\Scripts\Get-ConsoleAsText.ps1 | Out-File MyOutput.txt -encoding ascii"

如果要处理它并在批处理文件中执行某些操作,可以调用它并使用FOR命令处理输出。我将把这个练习留给你。
因此,例如,您的批处理文件将如下所示,以将控制台输出捕获到文件中:

c:\myProgramInC.exe
echo "Ending with error"
PowerShell -noprofile -sta -command "C:\Scripts\Get-ConsoleAsText.ps1 | Out-File MyOutput.txt -encoding ascii"
PAUSE
u3r8eeie

u3r8eeie2#

快速技巧是在for /f的上下文中执行,你甚至不需要一个批处理文件,你可以直接从cmd行执行:
for /f "tokens=*" %F in ('c:\myProgramInC.exe') do @echo %F >>myPrograminC.log
这将抑制所有输出,直到程序中止,然后才将所有消息写入文件。如果你的应用很少写日志消息(或者很快失败:-)),它应该可以工作。我用10000条线测试了它。
下面的批处理代码是基于同样的想法-请注意,即使它只写了最后5行,它仍然要扫描所有的行,所以我不确定它是否比上面的1行更好。

@echo off
setlocal 

for /f "tokens=*" %%P in ('c:\myProgramInC.exe') do (
 for /L %%C in (4,-1,1) do (
  set /A next=%%C+1
  call set line_%%next%%=%%line_%%C%%
 )
 set line_1=%%P
)
echo program ended abnormally! %date% %time%
for /L %%C in (5,-1,1) do call echo %%line_%%C%%
y0u0uwnf

y0u0uwnf3#

在C中,你可以很容易地做到这一点,使用ReadConsoleOutputCharacter函数。

hpxqektj

hpxqektj4#

最后,这就是我让它工作的原因。根据Harry约翰斯顿的建议,我搜索了ReadConsoleOutputCharacter函数的工作方式,并运行了下一个程序。

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <fstream>

#define BUFFER_SIZE 50000

int main(){
    HANDLE hOut;
    COORD location = {0, 0};
    char *buffer=NULL;
    DWORD numberRead;
    std::ofstream fileLog;

    buffer = new TCHAR[BUFFER_SIZE];

    if ( buffer==NULL )
    {
        printf("\nError: memory could not be allocated.\n");
        return 1;
    }

    fileLog.open ("logger.txt");

    if ( fileLog.fail() )
    {
        printf("\nError: file could not be opened.\n");
        return 1;
    }

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    ReadConsoleOutputCharacter(hOut, buffer, BUFFER_SIZE, location, &numberRead);

    fileLog << buffer ;

    free(buffer);
    fileLog.close();

    return 0;
}

我在互联网上找到了它的大部分代码,现在我没有URL(除了它来自另一个论坛网站,我不知道是否可以引用竞争对手的网站),但在谷歌上搜索一下并不难找到它。
我添加了它写入文件和内存分配的部分。它在VS C++ 6中运行得很好。
这对我来说很好,虽然可以更好。有两件事不太好
1.它将缓冲区中的所有内容写入一个文件,但不保留换行符,所以我得到一个文本文件,其中所有信息都在一行中。
1.无法定义要捕获多少行。它只需要从缓冲区的初始化到程序启动的点的一切,这并不坏,但由于这个应用程序应该在不同的服务器上运行,每个服务器都有不同的缓冲区用于每组命令提示符窗口,只是使用50000字节的缓冲区在某些情况下缓冲区较小时效率不高。我认为这可能是很多,但由于它是在真实的时间分配,也许是没有那么错误的使用尽可能多的内存。

j0pj023g

j0pj023g5#

如果有任何错误消息要报告回命令输出流,可以通过STDOUT(标准输出)和STDERR(标准错误)的重定向操作符轻松重定向。这取决于您是否希望捕获输出和/或错误。更有可能的是,你正在寻找这样的东西:

  • 命令2>>文件名

“2”是重定向操作符的一部分,表示STDERR将被重定向并附加到文件名。
来源、示例和文档:

  1. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
  2. http://ss64.com/nt/syntax-redirection.html
a0x5cqrl

a0x5cqrl6#

minde中立即出现的一件事是将命令行的输出重定向到文件:

c:\myProgramInC.exe >> myProgramInC.log

然后你可以看到日志文件中的内容。

相关问题