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!

TENNO
  • 165
  • 2
  • 11

1 Answers1

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);
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328