I have the following sample C# class:
public static class Class1
{
public static string Method1(Expression<Func<string>> efs)
{
return efs.Compile().Invoke();
}
}
To call this from C# it's as easy as:
Class1.Method1(() => "Hello World");
I can not for the life of me figure out how to call this from Powershell. My last attempt is:
Add-Type -Path "ClassLibrary1.dll"
$func = [Func[string]] { return "Hello World" }
$exp = [System.Linq.Expressions.Expression]::Call($func.Method);
[ClassLibrary1.Class1]::Method1($exp)
But this results in an error:
Exception calling "Call" with "1" argument(s): "Incorrect number of arguments supplied for call to method 'System.String lambda_method(System.Runtime.CompilerServices.Closure)'"
At C:\Users\Mark\Documents\Visual Studio 2015\Projects\ClassLibrary1\ClassLibrary1\test.ps1:4 char:1
+ $exp = [System.Linq.Expressions.Expression]::Call($func.Method);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException
+ $exp = [System.Linq.Expressions.Expression]::Call($func.Method);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException
I believe my $func is incorrect; any ideas?
Expression.Callthat takes a single argument. That is what the error is telling you as well.Cannot convert argument "efs", with value: "System.Func1[System.String]", for "Method1" to type "System.Linq.Expressions.Expression1[System.Func1[System.String]]", which is why I was trying to create anExpression` from theFunc.Func<string> func = () => "Hello World"; Expression.Call(func.Method);, it's using the signature:public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments), now I'm stuck trying to figure out how to call that...Static method requires null instance, non-static method requires non-null instance.Parameter name: method