Summary: Boe Prox shows how retrieve a seemingly lost Async object from a runspace.
How can I get the seemingly lost Async object created by BeginInvoke?
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()
$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)