本文介绍了从另一个 PowerShell 会话监视 PowerShell 会话中的作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

脚本循环执行以下步骤,假设这两个步骤都需要很长时间才能完成:

A script is executing the following steps in a loop, assume both steps take a long time to complete:

  1. $x = DoSomeWork;
  2. Start-Job -Name "Process $x" { DoSomeMoreWork $x;};

当然,第 1 步会阻止脚本,而第 2 步不会.我可以通过控制台轻松监控循环和步骤 1 的进度/状态.

Step 1 blocks the script and step 2 does not, of course.I can easily monitor the progress/state of the loop and step 1 through the console.

我还想做的是在批处理仍在执行时监视第 2 步启动的作业的作业状态.

What I'd also like to do is monitor the job status of jobs started by step 2 while the batch is still executing.

一般来说,是否可以从另一个会话附加"或查询另一个 powershell 会话?(假设监控会话没有产生工作会话)

In general, it is possible to 'attach' or query another powershell session from another session? (Assuming the monitoring session does not spawn the worker session)

推荐答案

如果我关注你,那么你就不能在两个不同的控制台实例之间共享状态.也就是说,不可能按照你想要的方式去做.但是,您不能从同一会话监视作业是不正确的.您可以通过作业内的事件发出信号:

If I'm following you, then you cannot share state between two different console instances. That is to say, it's not possible in the way you want to do it. However, it's not true that you cannot monitor a job from the same session. You can signal with events from within the job:

Start-Job -Name "bgsignal" -ScriptBlock {

    # forward events named "progress" back to job owner
    # this even works across machines ;-)
    Register-EngineEvent -SourceIdentifier Progress -Forward

    $percent = 0
    while ($percent -lt 100) {
        $percent += 10

        # raise a new progress event, redirecting to $null to prevent
        # it ending up in the job's output stream
        New-Event -SourceIdentifier Progress -MessageData $percent > $null

        # wait 5 seconds
        sleep -Seconds 5
    }
}

现在您可以选择使用 Wait-Event [-SourceIdentifier Progress]Register-EngineEvent -SourceIdentifier Progress [-Action { ... }] 或普通的老式交互式 Get-Event 用于查看和/或处理来自同一会话(如果您在远程服务器上启动作业,则使用不同的机器)的进度.

Now you have the choice to either use Wait-Event [-SourceIdentifier Progress], Register-EngineEvent -SourceIdentifier Progress [-Action { ... }] or plain old interactive Get-Event to see and/or act on progress from the same session (or a different machine if you started the job on a remote server.)

如果所有工作都在本地机器上完成,您也完全有可能不需要 Jobs 基础架构.查看我的一篇关于 RunspaceFactory 和 PowerShell 对象的旧博客文章,了解基本脚本线程池"实现:

It's also entirely possible you don't need the Jobs infrastructure if all work is being done on the local machine. Take a look at an old blog post of mine on the RunspaceFactory and PowerShell objects for a rudimentary script "threadpool" implementation:

http://www.nivot.org/2009/01/22/CTP3TheRunspaceFactoryAndPowerShellAccelerators.aspx

希望这会有所帮助,

-Oisin

这篇关于从另一个 PowerShell 会话监视 PowerShell 会话中的作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 05:01