2

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

1 Answers1

1

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()
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • tnks for your answer. and can u tell me how to close this thread and mange it like suspend or smth like this . –  Jan 08 '17 at 12:42
  • Please see the Scripting Guy blog I linked to in my answer. Post a new question if that doesn't help. – Ansgar Wiechers Jan 08 '17 at 13:06