简体   繁体   English

使用PowerShell远程运行控制台EXE并获取其进程ID和标准输出

[英]Run console EXE remotely with PowerShell and get its process ID and stdout

I use PowerShell to run a console EXE on a remote server and see its output like this: 我使用PowerShell在远程服务器上运行控制台EXE并查看其输出,如下所示:

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

This works, but gives me no way to kill the process, except connecting to the server via RDP. 这可行,但是除了通过RDP连接到服务器之外,我没有其他方法可以终止进程。 If I could just save its process ID to a file I should be able to kill it using Stop-Process . 如果我可以将其进程ID保存到文件中,则应该可以使用Stop-Process杀死它。 I tried this: 我尝试了这个:

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

The process runs, but now I don't see its standard output! 该过程正在运行,但现在看不到它的标准输出! When I use Start-Process locally (without Invoke-Command) I see the output. 当我在本地使用Start-Process(没有Invoke-Command)时,我看到了输出。

How can I get both the process ID and the standard output/error? 如何获取进程ID和标准输出/错误?

Use a background job . 使用后台作业 You can either start a local job to invoke a command on a remote host: 您可以启动本地作业来调用远程主机上的命令:

$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

or open a session to a remote host and start a local job there: 或打开与远程主机的会话并在此处开始本地作业:

Enter-PSSession -Computer $computer

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

Exit-PSSession

Job output can be received via Receive-Job : 可以通过Receive-Job接收作业输出:

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

You can terminate it via its StopJob() method: 您可以通过其StopJob()方法终止它:

$job.StopJob()

Remove-Job removes the job from the job list: Remove-Job从作业列表中删除作业:

Remove-Job $job

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM