1

I have a function call inside foreach loop, i do not want to wait till that function gets completed and need to make my foreach loop running, so i can achieve multi-threading concept in powershell. Is this possible? Please guide thanks.

foreach ($folders in $txtfilepath)

ftp_upload1 $foldertemp $Freelancername $articleid $Freelancermailfinal

As this is a upload function and wait time is more sometimes so i need to work as multi-thread so it will make all upload requests asap.

Ashwani Gusain
  • 55
  • 1
  • 10

3 Answers3

1

You should consider using PowerShell background jobs. It works like:

foreach ($folders in $txtfilepath) {
    Start-Job -ScriptBlock {
       ftp_upload1 $foldertemp $Freelancername $articleid $Freelancermailfinal
    }
}

But you probably want to receive the result etc. so take a look at about_jobs.

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • Thank you @Martin, but after adding background job function is not calling, its just skipping the function, please correct me if im missing something, i have same code whatever you hav provided. – Ashwani Gusain Nov 14 '19 at 12:21
  • You probably have to add the parameters as input to the script block. Just go and read the about_jobs document. – Martin Brandl Nov 14 '19 at 12:29
  • ok martin its working after providing some parameters, but again its calling function but not running foreach simultaneously, its waiting till function gets completes. – Ashwani Gusain Nov 14 '19 at 12:39
0

You may want to considering using ForEach-Object -Parallel switch:

Windows PowerShell 5.1 https://learn.microsoft.com/en-us/powershell/module/psworkflow/about/about_foreach-parallel?view=powershell-5.1

OR

PowerShell Core 7.0 Preview 5 https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Core/ForEach-Object?view=powershell-7

0

So Finally i got answer.

$FOO = {write-host "HEY"}
Start-Job -ScriptBlock $FOO | wait-job |Receive-Job

parameterize script blocks

$foo = {param($bar) write-host $bar}
Start-Job -ScriptBlock $foo -ArgumentList "HEY" | wait-job | receive-job

No doubt that i copied from some other post and here is the Link

Ashwani Gusain
  • 55
  • 1
  • 10