PowerTip: Get the Async Object Created by BeginInvoke

Doctor Scripto

Summary: Boe Prox shows how retrieve a seemingly lost Async object from a runspace.

Hey, Scripting Guy! Question How can I get the seemingly lost Async object created by BeginInvoke?

Hey, Scripting Guy! Answer Use Reflection to pull this information out of a Runspace object and get the Async object, which is required
           to use with EndInvoke().

$Runspace = [runspacefactory]::CreateRunspace()

$PowerShell = [powershell]::Create()


$PowerShell.Runspace = $Runspace



        Name = ‘Boe Prox’

        PowerShell = $True



#Intentionally forget to save this


#Time to retrieve our missing object

$BindingFlags = [Reflection.BindingFlags]’nonpublic’,’instance’

$Field = $PowerShell.GetType().GetField(‘invokeAsyncResult’,$BindingFlags)

$AsyncObject = $Field.GetValue($PowerShell)

#Now end the runspace



Discussion is closed.

Feedback usabilla icon