我正在编写一个脚本来ping多个站点,然后打开该文件以显示结果。我希望结果在他们完成时打开。相反,它会在打开文件之前等待所有作业完成。我也遇到过只会打开一些文件的问题。任何帮助将不胜感激
$count = 500
$sites = "www.google.com","8.8.8.8","127.0.0.1"
foreach ($site in $sites)
{
Remove-Item "C:\WFSupport\Self Service Tool\$site.txt"
start-job -Name $site -ScriptBlock { param ($count,$site) ping -n $count $site } -ArgumentList $count, $site
}
While ((Get-Job).State -match 'Running')
{
foreach ($Job in Get-Job | where {$_.HasMoreData})
{
$Jobname = $Job.Name
Receive-Job $Job | Out-File -Encoding ascii -Append "C:\WFSupport\Self Service Tool\$Jobname.txt"
}
Start-Sleep -Seconds 10
}
While ((Get-Job).State -match 'Completed')
{
foreach ($Job in Get-Job | where {$_.HasMoreData})
{
$Jobname = $Job.Name
Receive-Job $Job | Out-File -Encoding ascii -Append "C:\WFSupport\Self Service Tool\$Jobname.txt"
Invoke-Item "C:\WFSupport\Self Service Tool\$Jobname.txt"
}
Get-Job | Remove-Job
}
答案 0 :(得分:0)
这是因为While循环检查' Running'在所有作业都停止运行之前不会停止。下面的代码都不会在while循环结束之前运行。
while ((Get-Job).State -match 'Running') {
foreach ($job in Get-Job | where {$_.HasMoreData}) {
$jobname = $job.name
Receive-Job $Job | Out-File -Encoding ascii -Append "C:\WFSupport\Self Service Tool\$Jobname.txt"
if ($job.State -like 'Completed'){
Invoke-Item "C:\WFSupport\Self Service Tool\$Jobname.txt"
$job | remove-job
}
}
start-sleep -seconds 10
}