SoFunction
Updated on 2025-03-10

Example of PowerShell multithreaded front and backend jobs


$start = Get-Date

$task1 = { Start-Sleep -Seconds 4; Get-Service }
$task2 = { Start-Sleep -Seconds 5; Get-Service }
$task3 = { Start-Sleep -Seconds 3; Get-Service }

# run 2 in separate threads, 1 in the foreground
$thread1 = [PowerShell]::Create()
$job1 = $($task1).BeginInvoke()

$thread2 = [PowerShell]::Create()
$job2 = $($task2).BeginInvoke()

$result3 = Invoke-Command -ScriptBlock $task3

do { Start-Sleep -Milliseconds 100 } until ($ -and $)

$result1 = $($job1)
$result2 = $($job2)

$()
$()

$()
$()

$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds