0

I'm trying to call a function from a C# DLL via PowerShell. It requires an object array as parameter and I need to pass strings inside it, but I don't know how.

What I need to do:

C# version:

printCustom(new object[] {new string[] {"hello", "its", "working"}});

I need to call this function from powershell but how to pass the parameters?

printCustom([object[]]@(//now?//));
2
  • Is printCustom a static or instance method? Commented Mar 16, 2022 at 10:59
  • printCustom is static Commented Mar 16, 2022 at 10:59

1 Answer 1

3

Use the unary array operator , to wrap an enumerable type in an array - this will prevent PowerShell from unraveling the string-array when you then construct the array that'll actually get passed to the method:

[TargetType]::printCustom(@(,'hello its working'.Split()))

Let's test it:

# Generate test function that takes an array and expects it to contain string arrays

Add-Type @'
using System;

public class TestPrintCustom
{
  public static void printCustom(object[] args)
  {
    foreach(var arg in args){
      foreach(string s in (string[])arg){
        Console.WriteLine(s);
      }
    }
  }
}
'@

[TestPrintCustom]::printCustom(@(,"hello its working".Split()))

Which, as expected, prints:

hello
its
working
Sign up to request clarification or add additional context in comments.

7 Comments

well, thats kinda strange, im trying your way but apparently the functions doesnt get called anymore, without errors..
@root823746374 Can you perhaps update your question with the definition of the printCustom method?
Ok so, i found a way to make it working. The solution was to add [object[]] before your array creation. So: ([object[]]@(,'hello its working'.Split()))
Just to know, if i would like to pass the strings without using a single string and then split() how should i do it?
@root823746374 sure, it just gets a bit messy/unreadable: [TestPrintCustom]::printCustom(@(,[string[]]@('a','b','c')))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.