【问题标题】:Run console EXE remotely with PowerShell and get its process ID and stdout使用 PowerShell 远程运行控制台 EXE 并获取其进程 ID 和标准输出
【发布时间】:2016-06-21 05:38:24
【问题描述】:

我使用 PowerShell 在远程服务器上运行控制台 EXE,并看到它的输出如下:

 Invoke-Command -ComputerName %SERVER_NAME% -ScriptBlock { Set-Location "%EXE_DIR%" ; .\MyExe.exe %EXE_ARGS% }

这可行,但除了通过 RDP 连接到服务器外,我无法终止该进程。如果我可以将它的进程 ID 保存到一个文件中,我应该可以使用Stop-Process 来杀死它。我试过这个:

 Invoke-Command -ComputerName %SERVER_NAME% -ScriptBlock { Start-Process -NoNewWindow -PassThru -Wait -WorkingDirectory "%EXE_DIR%" "%EXE_DIR%\MyExe.exe" "%EXE_ARGS%" }

进程运行,但现在我看不到它的标准输出!当我在本地使用 Start-Process(没有 Invoke-Command)时,我看到了输出。

如何获取进程 ID 和标准输出/错误?

【问题讨论】:

  • 调查工作。 get-help about_Jobs,和-AsJob等

标签: powershell


【解决方案1】:

使用background job。您可以启动本地作业来调用远程主机上的命令:

$job = Start-Job -ScriptBlock {
  Invoke-Command -ComputerName $computer -ScriptBlock {
    Set-Location 'C:\some\folder'
    & 'C:\path\to\your.exe' $args
  } -ArgumentList $args
} -ArgumentList $argument_list

或打开与远程主机的会话并在那里启动本地作业:

Enter-PSSession -Computer $computer

$job = Start-Job -ScriptBlock {
  Set-Location 'C:\some\folder'
  & 'C:\path\to\your.exe' $args
} -ArgumentList $argument_list

Exit-PSSession

可以通过Receive-Job接收作业输出:

while ($job.HasMoreData) {
    Receive-Job $job
    Start-Sleep -Milliseconds 100
}

您可以通过其StopJob() 方法终止它:

$job.StopJob()

Remove-Job 从作业列表中删除作业:

Remove-Job $job

【讨论】:

  • 谢谢,远程运行作业听起来是个不错的主意,但是如何在运行时继续获得它的输出呢? Receive-Job 只是给了我到目前为止的输出。 Wait-Job 等待而不打印输出。基本上,我想要的行为就像 EXE 在控制台窗口中本地运行一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2011-12-31
相关资源
最近更新 更多