Skip to content

PowerShell class should have an InvokeAndClear() method #15008

Closed

Description

@rjmholt

Summary of the new feature/enhancement

A classic pitfall of the PowerShell class is doing something like this:

using (var pwsh = PowerShell.Create())
{
    DateTime? firstDate = pwsh.AddCommand("Get-Date").Invoke<DateTime?>().FirstOrDefault();
    DateTime? secondDate = pwsh.AddCommand("Get-Date").Invoke<DateTime?>().FirstOrDefault();

    Console.WriteLine($"1: {firstDate}");
    // secondDate is null??
    Console.WriteLine($"2: {secondDate}");
}

In this scenario, the PowerShell object's state is affected by the first AddCommand() call and we need to clear the commands. This is easily seen here but when pwsh is a field being shared between calls it can be subtle.

In a lot of my code I end up writing this:

static class PowerShellExtensions
{
    public static Collection<PSObject> InvokeAndClear(this PowerShell pwsh) => pwsh.InvokeAndClear<PSObject>();

    public static Collection<T> InvokeAndClear<T>(this PowerShell pwsh)
    {
        try
        {
            return pwsh.Invoke<T>();
        }
        finally
        {
            pwsh.Commands.Clear();
        }
    }
}

We should consider adding that to the PowerShell SDK, since I suspect this is a very common use case.

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Mar 12, 2021
  2. SeeminglyScience commented on Mar 12, 2021

    @SeeminglyScience
    Contributor

    Also the error, verbose, etc streams

  3. mklement0 commented on Mar 13, 2021

    @mklement0
    Contributor

    Just to spell it out, because the fact that your sample code actually does work confused me:

    The commands accumulate in the pwsh.Commands collection, and subsequent .Invoke() calls try to execute them all, in addition to accumulating stream output in pwsh.Streams across calls, as Patrick Meinecke (@SeeminglyScience) points out.

    Your second .Invoke() call is therefore roughly equivalent to:

    [powershell]::Create().AddCommand("Get-Date").AddCommand("Get-Date").AddArgument('1970-01-01').Invoke()

    which in turn is equivalent to:

    Get-Date | Get-Date

    and the latter just happens to work, because Get-Date also accepts a [datetime] instance via the pipeline, so this pipeline is in effect the same as just calling Get-Date alone.
    Adding a -Date argument to the 2nd GetDate call would surface the problem, however, because something like Get-Date | Get-Date 1970-01-01 indeed fails.


    As for the API surface and your extension method:

    If the intent is to also clear the streams, you cannot include .Streams.ClearStreams() in the .InvokeAndClear() method, as you would instantly wipe out the .Invoke() call's non-success stream output.

    So I wonder if something along the following lines is called for instead:

    A fluent .Reset() method that calls .Commands.Clear() and .Streams.ClearStreams() and returns the PowerShell instance itself, as the existing methods do.

    This means that resetting can then either be performed stand-alone:

    pwsh.Reset();  // same as: .Commands.Clear(); .Streams.ClearStreams(); return this;

    Or, fluently, as part of recurring invocations on a reusable PowerShell instance:

    pwsh.Reset().AddCommand("Get-Date").Invoke<DateTime?>().FirstOrDefault();
  4. Fs00 commented on Mar 15, 2021

    @Fs00
    Contributor

    I would definitely love to see a PowerShell.Reset() method as proposed by Michael Klement (@mklement0)!
    I've found myself doing pwsh.Commands.Clear(); pwsh.Streams.ClearStreams(); too (and once discovered the hard way that I had to).

  5. rjmholt commented on Mar 26, 2021

    @rjmholt
    CollaboratorAuthor

    Quick thought since I have the issue open:

    [Flags]
    public enum PowerShellClearOptions
    {
        None = 0x0,
        Commands = 0x1,
        Streams = 0x2,
    }
    
    ...
    
    public PowerShell Reset() => Reset(PowerShellClearOptions.Commands | PowerShellClearOptions.Streams);
    
    public PowerShell Reset(PowerShellClearOptions clearOptions)
    {
        if (clearOptions.HasFlag(PowerShellClearOptions.Commands))
        {
            Commands.Clear();
        }
    
        if (clearOptions.HasFlag(PowerShellClearOptions.Streams))
        {
            Streams.Clear();
        }
        
        return this;
    }

    I suggest that because in various scenarios, I don't want to clear the streams.

  6. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  7. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  8. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  9. added
    Resolution-No Activity
    on Nov 16, 2023
  10. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementNeeds-TriageResolution-No Activity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions