将写入过程添加到Get-Job/Wait-Job
我正在使用以下代码以120秒的超时显示PowerShell作业的结果。我想通过合并 Write-Progress
(基于完成的作业数)来增强此代码。我尝试使用此示例 ,当我尝试合并该代码时,Progress Bar在之后简要显示所有作业都已完成。
$Jobs = @()
$ForceStoppedIds = @{}
$Jobs += Get-Job
$Jobs | Wait-Job -Timeout 120 | Out-Null
$Jobs | ?{$_.State -eq 'Running'} | Stop-Job -PassThru | %{$ForceStoppedIds[$_.Id] = $true}
foreach ($Job in $Jobs) {
$Name = $Job.Name
$Output = (Get-Job -Name $Name | Receive-Job)
if ($ForceStoppedIds.Contains($Job.Id)) {
Write-Output "$($Name) - Device unable to process request within 2 minutes"
} else {
Write-Output $Output
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Wait -Job -TimeOut 120
将阻止线程,直到指定的超时或所有作业完成,因此无法显示进度并同时等待它们。我可以想到两种替代方案,第一个是创建一个 代理命令 /proxy功能围绕此cmdlet扩展其功能。
这些博客演示了如何做到:
您还可以从
另一种选择是定义自己的功能,该功能执行类似的工作,例如
wait-job
,但是,您可以添加一个基于2个条件运行的循环,而不是阻止线程diagnostics.stopwatch
为此)。$ obs
注意,下面的功能在大多数情况下应起作用,但是纯粹仅用于演示目的,不应依靠。
首先,我们定义一个可以用于显示进度的新功能,并根据超时等待我们的作业:
为了测试它,我们可以使用随机计时器创建一些作业:
Wait-Job -Timeout 120
will block the thread until the specified timeout or all jobs have completed, hence, is not possible to display progress and wait for them at the same time.There are 2 alternatives that I can think of, the first one would be to create a proxy command / proxy function around this cmdlet to extend it's functionality.
These blogs demonstrate how to do it:
proxy function
You can also follow the indications from this helpful answer.
The other alternative is to define your own function that does a similar work as
Wait-Job
but, instead of blocking the thread, you can add a loop that will run based on 2 conditions:Diagnostics.Stopwatch
for this).$jobs
List<T>
is still populated).Note, the function below should work in most cases however is purely for demonstration purposes only and should not be relied upon.
First we define a new function that can be used to display progress as well as wait for our jobs based on a timeout:
Then for testing it, we can create a few jobs with a random timer: