これを行うためのより洗練された方法があるかもしれませんが、PowerShellを使用している場合はこれで機能します。
以下のスクリプトを含むPowerShellスクリプトファイルを作成しGet-ConsoleAsText.ps1
ます。注、私はこのスクリプトを作成しませんでした。WindowsPowerShellブログ-キャプチャコンソール画面で見つけました。
#################################################################################################################
# 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