简体   繁体   中英

Powershell Multijob script. Make file open when job completes instead of waiting until all jobs complete

I'm writing a script to ping multiple sites and then open the file to show you the results. I would like the results to open as they finish. Instead it waits until all jobs are finished before opening the files. I've also had issues where it will only open some of the files. Any help would be appreciated

$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
}

This is because the While loop checking for 'Running' doesn't stop until all the jobs are stopped running. None of the code below that will run until that while loop finishes.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM