调用脚本块时,为什么我的接收作业调用挂起



我的代码无法到达最终输出行:

$downloadCommand = { 
$Response = Invoke-WebRequest -Uri "$someurl" -OutFile "$somelocation" 
0 
}
$job = Start-Job $downloadCommand
$sleeptime=10
While(Get-Job -State "Running")
{
#Get-Job -State "Running"
Start-Sleep -Seconds $sleeptime
}
Get-Job | Wait-Job
$result = Receive-Job -Job $job # <=== gets stuck here
Write-Host "Can't reach here"

知道我在这里做错了什么吗?我知道下载运行得很好,它肯定会跳出while循环。

奇怪的是,我不能让你的例子无限地挂起。也许你正在下载一些大文件?也许您的目标服务器正在无限期处理?

我修改了你的脚本以获取更多信息。

如果您正在检查作业状态并使用Start-Sleep等待,则脚本中不需要等待作业。

等待工作的正确方式:

$downloadCommand = { 
Invoke-WebRequest -Uri "$someurl" -OutFile "$somelocation";
}
$job = Start-Job $downloadCommand;

$sleepTime = 10;
while ((Get-Job | Where-Object Id -eq $job.Id).State -eq "Running")
{
Write-Host "Waiting next $sleepTime seconds for job $($job.Id) to finish...";
Start-Sleep -Seconds $sleepTime;
}
Receive-Job $job;

自Powershell 7.0以来的BTW-您可以使用Foreach对象-并行(https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7(

最新更新