Skip to content

Way to invoke a scriptblock with named parameters from C# #15004

Closed

Description

@rjmholt

Summary of the new feature/enhancement

Say I have a scriptblock like this:

{
    param(
        $a,
        $b
    )

    "a: $a"
    "b: $b"
}

And I want to invoke it from C#:

var sb = ScriptBlock.Create("...");
var parameters = new Hashtable
{
    { "a", "A" },
    { "b", "B" },
};

sb.Invoke(?);
InvokeCommand.InvokeScript(sb, ?);

using (var pwsh = PowerShell.Create())
{
    pwsh.<?>.AddParameters(parameters).Invoke();
}

Is there a way to do this currently in PowerShell, and if not can we have one?

The best way I've found to do this so far is to use reflection to create a FunctionInfo object around the scriptblock for invocation:

var sb = ScriptBlock.Create("param($a, $b) \"a: $a\",\"b: $b\"");
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

PropertyInfo runspaceExecutionContextProperty = typeof(Runspace).GetProperty("ExecutionContext", BindingFlags.Instance | BindingFlags.NonPublic);
Type ecType = runspaceExecutionContextProperty.PropertyType;

ConstructorInfo funcInfoCtor = typeof(FunctionInfo).GetConstructor(
    BindingFlags.NonPublic | BindingFlags.Instance,
    binder: null,
    new[] { typeof(string), typeof(ScriptBlock), ecType },
    modifiers: null);

object executionContext = runspaceExecutionContextProperty.GetValue(runspace);
var sbFuncInfo = (FunctionInfo)funcInfoCtor.Invoke(new object[] { string.Empty, sb, executionContext });

using (var pwsh = PowerShell.Create())
{
    pwsh.AddCommand(sbFuncInfo).AddParameters(new Dictionary<string, object>{ {"a", "A"}, {"b", "B"} });

    foreach (PSObject result in pwsh.Invoke())
    {
        Console.WriteLine(result);
    }
}

But this is very involved, messy, requires overhead and isn't public/officially supported.

Proposed technical implementation details (optional)

Some considerations:

  • While the PowerShell API is a good place for this, it doesn't currently have good support for scriptblocks (something which could be improved)
  • Other APIs do support scriptblocks well, such as CommandInvocationIntrinsics.InvokeScript and ScriptBlock.Invoke[WithContext] and it would be nice to extend those to enable named parameter passing since they allow simpler control of the execution context than the PowerShell API

Activity

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

    @mklement0
  3. SeeminglyScience commented on Mar 12, 2021

    @SeeminglyScience
    Contributor

    I've found myself wanting this a lot as well, but every time I go to request it I have a hard time justifying it. The only real reason you'd want to do this is to invoke a scriptblock in the current runspace while retaining original AST information for debugging.

    If you don't need the AST information, you can just ToString() it. If you aren't invoking in the current runspace, then runspace affinity is going to be a bit confusing for a public API.

    Side note, ScriptInfo is the command info equivalent for an anonymous script. Maybe just a public constructor that pulled execution context from TLS would be enough. Or from the scriptblock's affinity.

  4. rjmholt commented on Mar 12, 2021

    @rjmholt
    CollaboratorAuthor

    While there is currently no support for passing a dictionary of arguments - i.e. no support for splatting via the PowerShell class - a chain of .AddParameter() calls is akin to that, if more verbose.

    I believe AddParameters() does that.

    The only real reason you'd want to do this is to invoke a scriptblock in the current runspace while retaining original AST information for debugging.

    My primary reason is not wanting to rebuild a scriptblock. In my scenario, I'm taking in a user-provided scriptblock in a cmdlet and I want to execute it providing a set of parameters to choose from. I'd like that scriptblock to keep all of its context and metadata and not have the overhead of stringifying it just for PowerShell to construct a new one. That way, if something goes wrong in the execution, the error message makes sense to users.

  5. mklement0 commented on Mar 13, 2021

    @mklement0
    Contributor

    Thanks, Rob Holt (@rjmholt), now I understand, and thanks for the .AddParameters() hint; TIL.

    I'm taking in a user-provided scriptblock in a cmdlet and I want to execute it providing a set of parameters to choose from.

    Even in the case where a string is passed to .AddScript() (potentially incurring the cost of compilation again), as is currently the only option, it would indeed be nice to be able to pass (named) arguments to the script block, in a repeatable manner, so that a compiled-once script block in a cached PowerShell instance can be invoked repeatedly, with different arguments each time (this is somewhat related to your proposal #15008).

    So a potential API surface I see is:

    • Add an .AddScript(ScriptBlock sb) overload (don't know if there be dragons).

    • Add new .InvokeWithParameters() and .InvokeWithArguments() methods that supports passing named arguments / positional arguments to the script block in a given invocation.

    Currently, the only way to provide per-invocation input is to use the .Invoke() overloads that accept objects that act as pipeline input - there's no argument counterpart (only the "baking in" of arguments with .AddParameter(), ... that cannot later be replaced).

    To illustrate this based on your example:

    Instead of the following emulation of the described behavior:

    $ps = [powershell]::Create()
    
    $sb = { param($a, $b)  "a: $a", "b: $b" }
    
    # As a workaround, wrap the script block in another one that 
    # passes pipeline input to the original one via splatting.
    $sbWrapped = '$dictArgs=$($input); . {{ {0} }} @dictArgs' -f $sb.ToString()
    
    # Currently invariably stringifies the script block and rebuilds it.
    # As a workaround, pass the arguments dictionary via the *pipeline* to
    # enable repeated invocations.
    $ps.AddScript($sbWrapped).
        Invoke([array] @{ a = 'A'; b = 'B' })  # -> "a: A", "b: B"
    
    # Repeat invocation with different arguments:
    $ps.Invoke([array] @{ a = 'C'; b = 'D' })  # -> "a: C", "b: D"

    we would then be able to simplify to:

    $ps = [powershell]::Create()
    
    $sb = { param($a, $b)  "a: $a", "b: $b" }
    
    # [scriptblock] instance $sb is now passed as-is
    $ps.AddScript($sb).
        InvokeWithParameters(@{ a = 'A'; b = 'B' })
    
    # Repeat invocation with different arguments:
    $ps.InvokeWithParameters(@{ a = 'C'; b = 'D' })
  6. bpayette commented on Mar 15, 2021

    @bpayette
    Contributor

    Rob Holt (@rjmholt) ScriptBlock.Invoke() doesn't go through the parameter binder which is where named parameter binding is handled. It would be best/easiest/most consistent to allow you to add a scriptblock using the PowerShell API which would look like:

    [powershell]::Create().AddScript({param ($x, $y) "x is $x y is $y"}, $true).AddParameter("x", 10).AddParameter("y", 20).Invoke()

    Note that this actually works today from PowerShell because the ScriptBlock gets turned into a string and then back into a ScriptBlock. Given that the scriptblocks are cached there might not even be much of a performance penalty for the double-conversion.

  7. SeeminglyScience commented on Mar 15, 2021

    @SeeminglyScience
    Contributor

    It would be best/easiest/most consistent to allow you to add a scriptblock using the PowerShell API which would look like:

    I worry that adding a ScriptBlock overload would result in a lot of confusion. Supporting ScriptBlock directly would imply to me that SessionState, extent data, runspace affinity, etc would be honored. In out of process runspaces, this overload would probably just ToString, for in-process-but-not-current-thread runspaces, affinity would likely result in dead locks or state corruption.

    Also as you mentioned, it's common in PowerShell to rely on argument coercion here. So if a new overload were added it would most likely need to be the same as ToString() to avoid changing behavior of existing scripts (which doesn't solve the use case in the OP).

    Personally I'd like to see either:

    1. A public constructor on ScriptInfo. This is round about enough that you will likely already understand the caveats if you reach for this

    2. A static class following a similar pattern as the BCL's Unsafe and MemoryMarshal classes. This would make it abundantly clear that safety is the consumer's responsibility. Something like:

      namespace System.Management.Automation
      {
          public static class PSUnsafe // or CommandMarshal
          {
              public static ScriptInfo AsScriptInfo(ScriptBlock scriptBlock);
              public static ScriptInfo AsScriptInfo(ScriptBlock scriptBlock, Runspace affinity);
          }
      }
  8. mklement0 commented on Mar 15, 2021

    @mklement0
    Contributor

    Returning to something Rob Holt (@rjmholt) said in the OP:

    Other APIs do support scriptblocks well, such as CommandInvocationIntrinsics.InvokeScript and ScriptBlock.Invoke[WithContext]

    Rob Holt (@rjmholt), wouldn't introducing the following new ScriptBlock.InvokeWithContext() overload address your use case?

    public Collection<PSObject> InvokeWithContext (
      Dictionary<string, ScriptBlock> functionsToDefine, 
      List<System.Management.Automation.PSVariable> variablesToDefine, 
      IDictionary parameters // analogous to PowerShell.AddParameters()
    );

    That is, it would be the (extended) analog of PowerShell.AddParameters(), just like the existing overloads with their params object[] args parameter are the analog of multiple PowerShell.AddArgument() calls.

    Then perhaps there is no need to pass ScriptBlock instances as-is to a PowerShell instance, which would avoid the headaches that Patrick Meinecke (@SeeminglyScience) describes.


    However, independently - for the case where it's fine to pass a string to PowerShell.AddScript() and have that build the script block with the proper runspace affinity internally - there is still also an as-yet-unmet need to allow repeatable invocations to such a behind-the-scenes script block with new parameters on every invocation.

    Therefore, also introducing PowerShell.InvokeWithParameters(IEnumerable input, IDictionary parameters) and PowerShell.InvokeWithArguments(IEnumerable input, params object[] args) overloads makes sense to me - or perhaps even make do with new PowerShell.Invoke() overloads with additional parameters.

  9. SeeminglyScience commented on Mar 15, 2021

    @SeeminglyScience
    Contributor

    Side note, there is sort of a way to do this without reflection. This is the pattern I usually end up with:

    // From cmdlet parameters or similar
    ScriptBlock userScript;
    IDictionary parameters;
    
    using var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace);
    const string proxyScript = @"
          # I don't remember which of these are actually respected
    	  [System.Diagnostics.DebuggerHidden()]
    	  [System.Diagnostics.DebuggerStepThrough()]
    	  [System.Diagnostics.DebuggerNonUserCode()]
    	  param()
    	  end {
    	      $private:__p = $args[1]
    	      & $args[0] @__p
    	  }"@;
    
    pwsh.AddScript(proxyScript)
    	.AddArgument(userScript)
    	.AddArgument(parameters)
    	.Invoke();

    Not always applicable, but useful to have as a possible work around.

  10. SeeminglyScience commented on Mar 15, 2021

    @SeeminglyScience
    Contributor

    Rob Holt (@rjmholt), wouldn't introducing the following new ScriptBlock.InvokeWithContext() overload address your use case?

    It may not matter in every use case, but it's worth noting that the Invoke* methods have a lot of limitations (like end block only, very limited $MyInvocation, no error stream) and aren't very performant.

  11. mklement0 commented on Mar 15, 2021

    @mklement0
    Contributor

    Good to know, Patrick Meinecke (@SeeminglyScience) - still, it seems like it would make sense to have such an overload.

    So it looks like we have the following problems and potential solutions:

    • Inability to use named arguments with ScriptBlock.InvokeWithContext() and CommandInvocationIntrinsics.InvokeScript() (only positional ones are currently supported):

      • New overloads with a IDictionary parameters parameter could solve that problem.
    • Inability to pass a script block as-is to PowerShell.AddScript()

      • However, perhaps your workaround (which improves on my wrapper script-block technique by not stringifying the wrapped block but passing it as an argument instead) is sufficient for this particular use case - and its non-obviousness can implicitly serve as a signal that there be dragons.
    • Inability to pass per-invocation arguments via PowerShell.Invoke() - that currently only works for pipeline input.

      • For instance, two consecutive calls to ScriptBlock.Invoke() on a given, reusable script block with different parameters works just fine - $sb = { "[$args]" }; $sb.Invoke(1, 2); $sb.Invoke(3, 4) - but there's no way to do that via PowerShell.Invoke(), from what I understand (the.AddArgument/Parameter(s)() irrevocably bake the given arguments into the command).

      • Adding PowerShell.Invoke() overloads that accept per-invocation arguments via IDictionary parameters and params object[] args parameters could solve that problem.

  12. Keerthi-anusha commented on Jan 2, 2022

    @Keerthi-anusha

    Hi...
    I'm trying to invoke powershell script which was asking input parameters in powershell in c# how can pass input parameters from c#

  13. added
    WG-Engine
    on May 16, 2022
  14. SeeminglyScience commented on Jun 26, 2023

    @SeeminglyScience
    Contributor

    The engine WG discussed this and agree there should be a better solution than the work arounds currently in place in PSES (and other projects).

    We would like to avoid a direct method like .AddCommand(ScriptBlock) as that may give the wrong implications of support. Instead opting for an API like this:

    namespace System.Management.Automation
    {
        public static class PSUnsafe
        {
            public static ScriptInfo AsScriptInfo(ScriptBlock scriptBlock);
        }
    }

    This would allow a path to do this while making it clear the consumer has to understand what is potentially dangerous prior to using.

  15. removed
    Needs-Triage
    on Jun 26, 2023
  16. added
    Resolution-No Activity
    on Dec 24, 2023
  17. microsoft-github-policy-service commented on Dec 24, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if there is no further activity in 7 days, the issue will be closed automatically.

    Activity in this case refers only to comments on the issue. If the issue is closed and you are the author, you can re-open the issue using the button below. Please add more information to be considered during retriage. If you are not the author but the issue is impacting you after it has been closed, please submit a new issue with updated details and a link to this issue and the original.

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

Metadata

Metadata

Labels

Issue-EnhancementResolution-No ActivityWG-Engine

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions