好的,可能有一种更优雅的方法可以做到这一点,但假设你有 PowerShell,这将起作用。
创建一个名为的 PowerShell 脚本文件Get-ConsoleAsText.ps1
,其中包含以下脚本。注意,我没有创建这个脚本。我在Windows PowerShell 博客 - 捕获控制台屏幕上找到了它。
#################################################################################################################
# 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