【问题标题】:Powershell: Capture output from cmd at run timePowershell:在运行时从 cmd 捕获输出
【发布时间】:2014-07-26 14:04:54
【问题描述】:

是否可以在 cmd 运行时从命令行捕获输出?我有一个小 exe,它显示应使用脚本处理的各种消息,并在脚本运行时向用户显示一些信息。

我的脚本使用一些参数启动程序(exe)并检查进程是否仍在运行。在程序运行时,我想将所有消息捕获到一个变量中以进行处理。我找不到任何解决方案,“run.exe 2>&1”等的一些测试失败了。

有什么想法吗?

【问题讨论】:

  • 所以在 powershell 控制台中 $result = run.exe 不适合你?
  • Ive also tried (for example): $result = Start-Process "ping.exe" -ArgumentList "localhost" -Wait $result`
  • 我看过这个脚本。但它会在执行后捕获输出。我需要捕获(每行),而它正在进行中。
  • 不,使用 Tee-Object 我无法在 exe 运行时访问输出。

标签: powershell cmd command runtime


【解决方案1】:
$oInfo = New-Object System.Diagnostics.ProcessStartInfo
$oInfo.FileName  = "ping"
$oInfo.Arguments = "localhost"
$oInfo.UseShellExecute = $False
$oInfo.RedirectStandardOutput = $True

$oProcess = New-Object System.Diagnostics.Process
$oProcess.StartInfo = $oInfo

[Void]$oProcess.Start()

$bDone = $False

while (!$bDone)
{
    $char = $oProcess.StandardOutput.Read()

    if ($char -eq -1)
    {
        if ($oProcess.HasExited)
        {
            $bDone = $True
        }
        else
        {
            Wait-Event 1
        }
    }
    else
    {
        Write-Host -NoNewline "".PadLeft(1, $char)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2018-06-09
    • 2010-11-03
    • 2013-01-16
    相关资源
    最近更新 更多