Teknowledgist
Teknowledgist

Reputation: 403

How to stop an asynchronous PowerShell scriptblock?

I'm trying to have a Powershell script start a looping asynchronous script block and then do some "other stuff". When the "other stuff" is complete at some unknown later time, I want to stop/kill the script block.

I see the MS dev network info on the stopasych() method, but can't figure out how to apply it in Powershell.

A simple example:

$runspace = [runspacefactory]::CreateRunspace()
$ps = [powershell]::create()
$ps.runspace = $runspace

[void]$ps.addscript({
   $beep = "`a"
   for ($i = 1; $i -lt 5000; $i++) {
      $beep
      Start-Sleep -Seconds 10
   }
})
$runspace.open()
$asyncObject = $ps.beginInvoke()

Copy-Item "c:\bigdata" "\\server\share"

That gets me started, but when the copying is done, I want to kill the beeping. I can't reverse these (i.e. do the "copying" in the background) because there ends up with a delay until the condition, $ps.InvocationStateInfo.state is checked again.

Can anyone help? BTW, I'd like to stick to PoSh v2.

Upvotes: 4

Views: 2487

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175084

Just like Invoke() has an asynchronous Begin/End pair, so does Stop().

You can wrap them like this to stop invocation:

$ps.EndStop($ps.BeginStop($null,$asyncObject))

Upvotes: 2

Related Questions