Powershell Start-job 同步输出 [英] Powershell Start-job synchronous output

查看:112
本文介绍了Powershell Start-job 同步输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动作业的 powershell 脚本

I have a powershell script that starts a job

start-job -scriptblock { 
  while($true) {
    echo "Running"
    Start-Sleep 2
  }
}

然后它继续执行脚本的其余部分.

and then it continues executing the rest of the script.

那个工作,是一种监控那个进程的 PID 的工作.

That job, is kind of a monitoring one for the PID of that process.

我想每 n 秒同步打印一次 PID,而不必结束作业.

I would like to synchronously print the PID every n seconds, without having to end the job.

例如,当脚本的其余部分正在执行时,我希望在我的控制台中看到输出.

For example, as the rest of the script is being executed, i would like to see output in my console.

在 powershell 中可以实现类似的功能吗?

Is something like that possible in powershell?

谢谢.

推荐答案

是的,您可以使用事件:

Yes, you can use events:

$job = Start-Job -ScriptBlock { 
  while($true) {
    Register-EngineEvent -SourceIdentifier MyNewMessage -Forward
    Start-Sleep -Seconds 3
    $null = New-Event -SourceIdentifier MyNewMessage -MessageData "Pingback from job."
  }
}

$event = Register-EngineEvent -SourceIdentifier MyNewMessage -Action {
  Write-Host $event.MessageData;
}

for($i=0; $i -lt 10; $i++) {
  Start-Sleep -Seconds 1
  Write-Host "Pingback from main."
}

$job,$event| Stop-Job -PassThru| Remove-Job #stop the job and event listener

归功于这个答案.其他有用的链接:

Credit goes to this answer. Other useful links:

这篇关于Powershell Start-job 同步输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆