如何让代码将所有输出发送到单个CMD窗口?

时间:2016-02-25 20:01:12

标签: windows powershell

我有一个简单的Java客户端&服务器对(此处称为FixedMessageSequenceClientFixedMessageSequenceServer)。我希望它们的输出都转到同一个CMD窗口。但是,因为它们是单独的Windows。到目前为止,这是我的代码:

$serviceStart = New-Object System.Diagnostics.ProcessStartInfo
$serviceStart.RedirectStandardInput = $true
$serviceStart.UseShellExecute = $false; #needed to redirect console input
#$serviceStart.FileName = ""
$serviceStart = Start-Process java  FixedMessageSequenceServer 
$serviceStart.WorkingDirectory = "C:\Java_Scratch2\FixedMessageSequenceServer.java"

$serviceStart.Arguments = "AsConsole"

$serviceStart = [System.Diagnostics.Process]::Start($serviceStart)

$service2Start = New-Object System.Diagnostics.ProcessStartInfo
$service2Start.RedirectStandardInput = $true
$service2Start.UseShellExecute = $false #needed to redirect console input
#$service2Start.FileName
$service2Start = Start-Process java  FixedMessageSequenceClient
$service2Start.WorkingDirectory = "C:\Java_Scratch2\FixedMessageSequenceClient.java"

$service2Start.Arguments = "AsConsole" 

$service2Start = [System.Diagnostics.Process]::Start($service2Start)

#$JavaServer = Start-Process java FixedMessageSequenceClient

我以为那行

$service2Start.RedirectStandardInput = $true

会强制输出转到一个CMD窗口。

1 个答案:

答案 0 :(得分:2)

将这两个进程作为background jobs启动,并定期获取作业的输出:

$server = Start-Job -Name 'fmsserver' -ScriptBlock {
  Set-Location 'C:\Java_Scratch2\FixedMessageSequenceServer.java'
  & java FixedMessageSequenceServer AsConsole
}
$client = Start-Job -Name 'fmsclient' -ScriptBlock {
  Set-Location 'C:\Java_Scratch2\FixedMessageSequenceClient.java'
  & java FixedMessageSequenceClient AsConsole
}

while ($server.State, $client.State -contains 'running') {
  if ($server.HasMoreData) { Receive-Job $server }
  if ($client.HasMoreData) { Receive-Job $client }
  Start-Sleep -Milliseconds 100
}

# fetch remaining output after completion
Receive-Job $server
Receive-Job $client

# clean up
Remove-Job $server
Remove-Job $client