How to add a callback function to an asynchronous job in powershell and get return data

后端 未结 3 1499
孤城傲影
孤城傲影 2021-01-16 01:38

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.

3条回答
  •  终归单人心
    2021-01-16 02:10

    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";
    

提交回复
热议问题