Repository navigation
Closed
Labels
Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime
Description
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
PowerShellAPI 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.InvokeScriptandScriptBlock.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 thePowerShellAPI
Reacted by Staffan Gustafsson and Flavien MICHALECZEK
Metadata
Metadata
Assignees
Labels
Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime
Activity
mklement0 commentedon Mar 12, 2021
SeeminglyScience commentedon Mar 12, 2021
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,
ScriptInfois 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.rjmholt commentedon Mar 12, 2021
I believe
AddParameters()does that.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.
mklement0 commentedon Mar 13, 2021
Thanks, Rob Holt (@rjmholt), now I understand, and thanks for the
.AddParameters()hint; TIL.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 cachedPowerShellinstance 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:
we would then be able to simplify to:
bpayette commentedon Mar 15, 2021
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 thePowerShellAPI which would look like: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.
SeeminglyScience commentedon Mar 15, 2021
I worry that adding a
ScriptBlockoverload would result in a lot of confusion. SupportingScriptBlockdirectly would imply to me thatSessionState, extent data, runspace affinity, etc would be honored. In out of process runspaces, this overload would probably justToString, 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:
A public constructor on
ScriptInfo. This is round about enough that you will likely already understand the caveats if you reach for thisA static class following a similar pattern as the BCL's
UnsafeandMemoryMarshalclasses. This would make it abundantly clear that safety is the consumer's responsibility. Something like:mklement0 commentedon Mar 15, 2021
Returning to something Rob Holt (@rjmholt) said in the OP:
Rob Holt (@rjmholt), wouldn't introducing the following new
ScriptBlock.InvokeWithContext()overload address your use case?That is, it would be the (extended) analog of
PowerShell.AddParameters(), just like the existing overloads with theirparams object[] argsparameter are the analog of multiplePowerShell.AddArgument()calls.Then perhaps there is no need to pass
ScriptBlockinstances as-is to aPowerShellinstance, 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)andPowerShell.InvokeWithArguments(IEnumerable input, params object[] args)overloads makes sense to me - or perhaps even make do with newPowerShell.Invoke()overloads with additional parameters.SeeminglyScience commentedon Mar 15, 2021
Side note, there is sort of a way to do this without reflection. This is the pattern I usually end up with:
Not always applicable, but useful to have as a possible work around.
SeeminglyScience commentedon Mar 15, 2021
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.mklement0 commentedon Mar 15, 2021
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()andCommandInvocationIntrinsics.InvokeScript()(only positional ones are currently supported):IDictionary parametersparameter could solve that problem.Inability to pass a script block as-is to
PowerShell.AddScript()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 viaPowerShell.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 viaIDictionary parametersandparams object[] argsparameters could solve that problem.Keerthi-anusha commentedon Jan 2, 2022
Hi...
I'm trying to invoke powershell script which was asking input parameters in powershell in c# how can pass input parameters from c#
SeeminglyScience commentedon Jun 26, 2023
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:This would allow a path to do this while making it clear the consumer has to understand what is potentially dangerous prior to using.
microsoft-github-policy-service commentedon Dec 24, 2023
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.