Home > Back-end >  Running Multiple Functions parallelly in PowerShell
Running Multiple Functions parallelly in PowerShell

Time:09-30

I have created a GUI using powershell to retrieve information from a remote server. As part of that I have 3 text boxes which populate the data when clicked on the button.

When clicked on the button it executes a function lets call it Function 'X'. Function X calls 3 more functions (lets calls them A, B and C) which intern populate those 3 textboxes.

My question is that how do I run those 3 function simultaneously as currently they run one at a time.

Function X(
   Function A
   Function B
   Function C

)

Example

Function A{
    $txtResultSvc.ForeColor=[Drawing.Color]::Black
    $res=Check-Something
    if($res -eq 999){
        $txtResultSvc.ForeColor=[Drawing.Color]::Red
        $txtResultSvc.Text=$blank
    }
    Else{
        $server="Servername"
        Disable-AllButtons
        $txtResultSvc.Text="Connecting to $server"
        if(Test-Connection -ComputerName $server -Count 2 -Quiet){
            $txtResultSvc.ForeColor=[Drawing.Color]::Green
            $txtResultSvc.Text="Connected. Getting System Info from $server"
            $resulttextsvc=Get-ABC -store $server
            if($txtResultSvc.Text -ne $null){
                $txtResultSvc.Text=""
                $txtResultSvc.ForeColor=[Drawing.Color]::Black
                $txtResultSvc.AppendText((($resulttextsvc| Out-String -Width 1100).Trim()))
                $txtResultSvc.SelectionStart=0
            }
        }
        Else{
            $txtResultSvc.ForeColor=[Drawing.Color]::Red
            $txtResultSvc.Text="Unable to connect to $server"
        }
    }
}

CodePudding user response:

Thanks for all the help. I ended up going the runspaces route. Followed the below videos -

https://www.youtube.com/watch?v=s6A9KuEM324

CodePudding user response:

Here's the threadjob method (install-module threadjob) for powershell 5.1. It takes 5 seconds total, showing that the three functions run in parallel.

$init = {
  function function1 { sleep 5; 'function 1' }
  function function2 { sleep 5; 'function 2' }
  function function3 { sleep 5; 'function 3' }
}

get-date
$(
  start-threadjob -init $init { function1 }
  start-threadjob -init $init { function2 }
  start-threadjob -init $init { function3 }
) | receive-job -wait -auto
get-date


Thursday, September 29, 2022 1:37:52 PM
function 1
function 2
function 3
Thursday, September 29, 2022 1:37:57 PM
  • Related