0

I have a list of functions that get called in loop $listoffunctions. Some are run in RunspacePool (multithread) while others run in the main thread. The ones that run in main thread are forms with buttons.

I need the ones that run in the main thread (interactive forms) to finish before continuing the foreach loop with other functions in list.

$listoffunctions contains strings of function names with parameters sometimes like RichTextDocumentNewContext -Show and UseStoreOpenWith -Hide and PostActions.

$WinAPIList contains a list of function names that call up a form with buttons (form XAML and buttons) for user to interact with. So it contains function names like ScheduledTasks -Disable and ScheduledTasks -Enable. Foreach loop should wait for the user to finish interacting with this form completely and its background commands to finish.

foreach ($singlefunction in $listoffunctions)
{
    # PowerShell
    $PowerShell = [PowerShell]::Create() 
    $PowerShell.RunspacePool = $RunspacePool
    
    # These functions run in main thread which names are found in WinAPIList
    if ($WinAPIList -contains $singlefunction){
        [void]$PowerShell.AddScript({Write-Output "Main Thread Run"})

        # This runs the function but I need it to wait for it to end before continue foreach loop   
        #$sb = [scriptblock]::Create($singlefunction)
        #& $sb
        
        # This does not work
        Start-Job -Name Job1 -ScriptBlock {$singlefunction}
        Wait-Job -Name Job1
        
    }
    # These function are run in the RunspacePool (Multithread)
    else{
        # Add script (function) to run

        [void]$PowerShell.AddScript($singlefunction)
    }
}

This does not work

# This does not work
Start-Job -Name Job1 -ScriptBlock {$singlefunction}
Wait-Job -Name Job1
4
  • We dont know what $listoffunctions or $WinAPIList are. Better provide a minimal reproducible example of the issue instead of making us guess things Commented Nov 17, 2023 at 2:14
  • Sorry. I added more information. Thank you so much Santiago Squarzon Commented Nov 17, 2023 at 2:32
  • 2
    & ([scriptblock]::Create($singlefunction)) should run synchronously - is that not what you want, or does the function itself launch something asynchronously? Unless your functions are in auto-loading modules, Start-Job won't see them; if they are, you'd need to use Start-Job ([scriptblock]::Create($singlefunction)), but that is just a much less efficient way of invoking them, compared to direct invocation. Commented Nov 17, 2023 at 2:46
  • Thanks for this information. It is running synchronously. I thought is wasn't. heheh. My bad observation. Commented Dec 11, 2023 at 18:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.