Search code examples
wpfmultithreadingpowershellstart-job

Powershell - updating textbox from start-job


I've been working on moving over a WPF program I wrote in C# over to PowerShell, and I'm having a little issue with appending text in my RichTextBox from Start-Job It looks like I can call the Set-RichTextBox where ever, except for inside the scriptblock. Is there a workaround?

#outside the ScriptBlock
Set-RichTextBox -message "This does work"
#outside the ScriptBlock

$job = Start-Job -ScriptBlock {

function Set-RichTextBox
{
  param (
     [System.String]
     $message
  )
     $richTextBox1.Dispatcher.invoke([action]{       
     $richTextBox1.AppendText($message)      
     },"Normal")
 }

  Set-RichTextBox -message "This doesn't work"
  }

I can call RichTextBox anywhere except for within the Start-Job, I do not get any error messages. Any idea what I'm doing wrong here?


Solution

  • to me it seems it works:

    Remove-Job *
    
    $job = Start-Job -Name Test -ScriptBlock {
    
        function Set-RichTextBox
        {
            param ([string]$message)
    
            $message
        }
    
        Set-RichTextBox -message "This should work..."
    }
    
    Start-Sleep 5
    Get-Job |Where-Object {$PSItem.Name -eq "Test"} |Receive-Job
    

    you might wanna have a look at: PowerShell: Creating Custom Objects

    also these may or may not be related: