You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动捕获PowerShell会话的终端显示内容至文件?

如何自动捕获与终端显示一致的PowerShell会话内容

针对Start-Transcript的改进方案

Start-Transcript是官方原生工具,你遇到的两个核心问题可以通过以下配置解决:

  • 捕获Write-Host输出:在启动转录前执行$InformationPreference = 'Continue',PowerShell 5.1及以上版本中,Write-Host的输出会被重定向到信息流,从而被Start-Transcript捕获。若使用更早版本,可将Write-Host替换为Write-Information -MessageData "内容" -InformationAction Continue,同样能被转录记录。
  • 过滤已抑制的错误:如果已通过$ErrorActionPreference = 'SilentlyContinue'或命令参数-ErrorAction SilentlyContinue抑制错误,可在启动转录时添加-IncludeInvocationHeader $false减少冗余,同时确保被抑制的错误流被重定向到null(如命令后追加2>$null),避免转录文件混入无效错误内容。

示例执行代码:

$InformationPreference = 'Continue'
Start-Transcript -Path ".\session_log.txt" -IncludeInvocationHeader $false
# 执行测试命令
Write-Host "这是Write-Host输出内容"
Get-Item non_existent_file -ErrorAction SilentlyContinue
Stop-Transcript

自动导出缓冲区内容的脚本

若希望无需手动执行,自动在会话结束时导出终端缓冲区内容,可通过以下步骤实现:

  1. 创建自动捕获脚本AutoCaptureSession.ps1:
# 注册PowerShell退出事件,自动导出缓冲区
Register-EngineEvent PowerShell.Exiting -Action {
    $buffer = $host.UI.RawUI.GetBufferContents()
    $logPath = ".\session_buffer_$(Get-Date -Format 'yyyyMMddHHmmss').txt"
    $buffer | Out-File -FilePath $logPath -Encoding UTF8
} | Out-Null

# 可选:扩大缓冲区容量,避免丢失早期内容
$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size(120, 9999)
  1. 将脚本加入PowerShell配置文件:
    • 打开配置文件:notepad $PROFILE
    • 添加一行:. "C:\实际路径\AutoCaptureSession.ps1"
    • 保存后,每次启动PowerShell都会自动注册退出事件,会话结束时自动生成缓冲区日志。

自定义提示符与命令日志方案

如果需要更精细的内容控制,可通过自定义提示符和事件监听,分别记录提示符、命令和输出:

$logFile = ".\custom_session_log.txt"

# 自定义提示符,同时记录到日志
function prompt {
    $currentPrompt = "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
    Add-Content -Path $logFile -Value $currentPrompt
    return $currentPrompt
}

# 监听命令启动事件,记录输入的命令
Register-EngineEvent -SourceIdentifier PowerShell.CommandStarted -Action {
    Add-Content -Path $logFile -Value $event.MessageData.CommandLine
} | Out-Null

# 监听命令完成事件,记录输出内容
Register-EngineEvent -SourceIdentifier PowerShell.CommandCompleted -Action {
    if ($event.MessageData.Output) {
        Add-Content -Path $logFile -Value $event.MessageData.Output
    }
} | Out-Null

注:此方案对表格等复杂格式的还原度有限,需根据实际需求调整输出处理逻辑。

内容的提问来源于stack exchange,提问作者CRice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 18:56:09