PowerTip: Get the Async Object Created by BeginInvoke


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 = ::Create()

$Runspace.Open()

$PowerShell.Runspace = $Runspace

[void]$PowerShell.AddScript({

    [pscustomobject]@{

        Name = ‘Boe Prox’

        PowerShell = $True

    }

})

#Intentionally forget to save this

$PowerShell.BeginInvoke()

#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

$PowerShell.EndInvoke($AsyncObject)

Comments (0)

Skip to main content