powershellclipboardapartments

How can I set thread in PowerShell with executable scriptblock and ApartmentState argument?


How can I set thread and start it with some executable code with ApartmentState = "STA"? I just find this method but I don't know how I can pass my scriptblock to it.

$r = [RunspaceFactory]::CreateRunspace()
$r.ApartmentState = 'STA'
$r.Open()

I need to get clipboard text in this thread, like this:

$getclipboardtext = [System.Windows.Clipboard]::GetText()
$getclipboardtext | Out-File c:\examplepath

I also tried Start-Job.


Solution

  • You need to put the runspace in a PowerShell instance (see here):

    $ps = [PowerShell]::Create()
    $ps.Runspace = $r
    [void]$ps.AddScript($sb)
    $ps.Invoke()
    $ps.Dispose()
    

    where $r is the runspace you opened and $sb is the scriptblock you want to execute.

    You also have an error in your scriptblock. The Clipboard class is part of the System.Windows.Forms namespace, so it's System.Windows.Forms.Clipboard, not System.Windows.Clipboard. Plus, you need to load the respective assembly first.

    Full example:

    $sb = {
      Add-Type -Assembly 'System.Windows.Forms'
      [Windows.Forms.Clipboard]::GetText() | Out-File 'C:\path\to\output.txt'
    }
    
    $ps = [PowerShell]::Create()
    $ps.Runspace = [RunspaceFactory]::CreateRunspace()
    $ps.Runspace.ApartmentState = 'STA'
    $ps.Runspace.Open()
    [void]$ps.AddScript($sb)
    $ps.Invoke()
    $ps.Dispose()