Skip to content

PowerShell.Stop() behaviour causes very different results between PowerShell.Invoke() and PowerShell.InvokeAsync() #15173

@rjmholt

Description

@rjmholt

Steps to reproduce

[Cmdlet(VerbsLifecycle.Invoke, "Example")]
public class InvokeScriptCommand : PSCmdlet
{
    [Parameter]
    public SwitchParameter Async { get; set; }

    protected override void EndProcessing()
    {
        using (var powershell = PowerShell.Create())
        {
            powershell.AddScript("1;2;3;sleep 10;4;5;6");

            Task<IList<PSObject>> task = null;
            if (Async)
            {
                task = RunAsync(powershell);
            }
            else
            {
                task = Run(powershell);
            }

            Thread.Sleep(2000);

            powershell.Stop();

            foreach (PSObject result in task.GetAwaiter().GetResult())
            {
                Console.WriteLine(result);
            }
        }
    }

    private Task<IList<PSObject>> RunAsync(PowerShell powershell)
    {
            return powershell.InvokeAsync()
                .ContinueWith(psTask =>
                {
                    return (IList<PSObject>)psTask.Result;
                });
    }

    private Task<IList<PSObject>> Run(PowerShell powershell) => Task.Run(() => (IList<PSObject>)powershell.Invoke());
}
> Invoke-Example -Async
Invoke-Example: One or more errors occurred. (The pipeline has been stopped.)

> Invoke-Example
1
2
3

Expected behavior

Both the async and sync executions should do the same thing.

Actual behavior

The sync execution returns a partial result and the async execution throws a PipelineStoppedException.

What's more, when a PSDataCollection<PSObject> is passed into the InvokeAsync() call, no results are ever inserted and the DataAdding and DataAdded events are never fired. I passed my collection to the input parameter; passing it to the output parameter works...

Environment data

This is with the PowerShell 7.2.0-preview.4 (both as a standalone app with the SDK and as a cmdlet with the exe).

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions