Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all articles
Browse latest Browse all 3333

PowerTip: Get the Async Object Created by BeginInvoke

$
0
0

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()

$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)


Viewing all articles
Browse latest Browse all 3333

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>