Reputation: 25
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
Upvotes: 0
Views: 131