I\'ve been searching around the internet and combining lots of different pieces of code, but I\'m just not succeeding at creating a callback for my asynchronous job.
I ended up changing the Invoke method, and the Event registerer to pass a parameter that contains the output.
Although this is probably not the cleanest method, it does work for me (with some checks in place that the data isn't accessed before it's actually available of course.
$Object = New-Object 'System.Management.Automation.PSDataCollection[psobject]';
$jobs += $PSinstance.BeginInvoke($Object, $Object);
Add-Member -InputObject $PSinstance -MemberType NoteProperty -Name EventSubscriber -Value (
Register-ObjectEvent -InputObject $PSinstance -EventName InvocationStateChanged -MessageData $Object -Action {
# Ignore initial state change on startup
if ($event.InvocationStateInfo.State -eq [System.Management.Automation.PSInvocationState]::Running) {
return;
}
Write-Host "event called";
Write-Host $Object.StatusCode;
}
);
# Can be accessed after the invoke has finished.
Write-Host "The result is: $Object.StatusCode";