0
votes

I have written script to split one file (Containing hostnames) into ten files, perform ping (i.e. powershell test-connection command) to hostnames in each file. To speed up the process, i used start-job command to process each file hostnames. If I remove the start-job command the scripts works just fine, as desired. But when i use the start-job command, the array used inside the "scriptblock" does not return the desired output. Instead, it remains empty. Following is the partial script (for only one file processing). Please guide, what Am I missing here?

Start-Job -Name "Ping-Part-1" -ScriptBlock {
    foreach ($Comp1 in $file_part1_content) {
        If (test-Connection -ComputerName $Comp1 -Count 1 -Quiet) {
                $project1 = Create-New-Object
                $project1.AliveStatus = "Alive"
                $project1.Hostname = $Comp1
                $resultsarray_file1 += $project1
            }
            Else {
                $project1 = Create-New-Object
                $project1.AliveStatus = "Not Alive"
                $project1.Hostname = $Comp1
                $resultsarray_file1 += $project1
            }
        }
    }
1
Create-New-Object? there's no such thing4c74356b41
Start-Job works by creating new process with separate Runspace with separate variables ($resultsarray_file1 in particular).user4003407
it is a custom written functionFakhar ul Hassan
function Create-New-Object { New-Object PSObject -Property @{ AliveStatus = '' Hostname = '' } }Fakhar ul Hassan

1 Answers

0
votes

Couple of things are wrong with this. By default the variables you use inside the job are not available within your powershell session (and vice versa btw). So you've got multiple issues. You're not putting any variables in the job and you're not retrieving any out of the job.

Also you've put the start-job in the wrong place. You're now starting 1 job with the entire foreach loop in there. I'm assuming you want to process each computer separately. So you should start the job inside the foreach loop.

I wrote a blogpost on this some time ago that fits your scenario. You can find it here.