0

I need to pass a string array as an argument to a PowerShell script from Java using Runtime.getRuntime().exec(cmd)

that array holds some values like:

String[] users = new String[] {"Jon", "Adam"};

and the PowerShell script test.ps1:

param(
  # ... other parameters defined here
  [parameter(Mandatory=$false)]
  [string[]] $names
)

# the rest of the script

What is the right way to pass that array?

Note:

I tried to a pass in the cmd parameter like that:

  1. by passing the argument as a separate tokens without comma:

    cmd.add("-names");
    cmd.add("Jon");
    cmd.add("Adam");
    // only "Jon" received in $names
    
  2. by appending the tokens with comma:

    cmd.add("-names")
    cmd.add("Jon"
    cmd.add(","
    cmd.add("Adam");
    // only "Jon" received in $names
    
  3. by appending the arguments as a comma-separated string:

    cmd.add("-names");
    cmd.add("Jon, Adam");
    // single string received contains "Jon, Adam"
    
  4. by appending parameter and comma-separated arguments as a single string:

    cmd.add("-names Jon, Adam");
    // return an error
    

but none of the above is working.

Update 1:

I know now that I can pass the arguments on two ways from the console:

test.ps1 -names Jon,Adam
test.ps1 -names ("Jon","Adam")`

and I tried to pass the array like:

cmd.add("-names")
cmd.add("(\"Jon\", \"Adam\")");

but that also isn't working. The script receives them as a single string!

9
  • And what do you expect to receive if you issue a "echo $names"?
    – Heri
    Commented Oct 30, 2016 at 18:13
  • @PetSerAl you are right, it's a typo and I updated the question
    – TENNO
    Commented Oct 30, 2016 at 18:16
  • @Heri, I expect to see both names in that array [I updated the script in the question]
    – TENNO
    Commented Oct 30, 2016 at 18:17
  • maybe this anwer helps: stackoverflow.com/questions/7152740/…
    – Heri
    Commented Oct 30, 2016 at 18:23
  • @Heri It should work if I'm passing it form another script, but it's a different case
    – TENNO
    Commented Oct 30, 2016 at 18:25

1 Answer 1

0

You need to quote the arguments twice. My Java is a little rusty, but I think something like this should do:

String[] users = new String[] {"Jon", "Adam"};
String script = "C:/path/to/your.ps1"
String cmd = "powershell.exe " + script + " -names " +
             "\"'" + String.join("'\",\"'", users) + "'\"";
Process proc = Runtime.getRuntime().exec(cmd);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.