ayush
ayush

Reputation: 14568

Java Process Builder Command Error, Escaping double quotes

Following statement works fine when typed in CMD

wmic /node:IP /user:Someuser /password:PWD Process Call Create "cmd /c echo 'Required_Info' %SystemDrive% %SystemRoot%"

I am trying to excecute the same through java process builder. Here is the code.

//some code
String wmic_cmd = "Process Call Create";
String wmic2 = " \"cmd /c echo 'Required_Info' %SystemDrive% %SystemRoot% \"";
cmdTokens.add(wmic_cmd);
cmdTokens.add(wmic2);
/*debug and checked the value of cmdTokens array - it was
[wmic, /node:10.0.0.0, /user:Someuser, /password:PWD, Process Call Create,  "cmd /c echo 'Required_Info' %SystemDrive% %SystemRoot% "] 
*/
ProcessBuilder pb = new ProcessBuilder(cmdTokens.toArray(new String[]{}));
Process proc = pb.start();

When i check the error stream of proc i get the following -

Process Call Create - Alias not found.

This indicates a syntax error for WMIC. So Something is going wrong while sending the command string array to process builder.

Any ideas??

Upvotes: 2

Views: 3863

Answers (1)

fge
fge

Reputation: 121790

Given your command line and what you want to do, this is not how to do it. Use:

final List<String> cmd = Arrays.asList("wmic", "/node:IP", "/user:Someuser",
    "/password:PWD", "Process", "Call", "Create",
    "cmd /c echo 'Required_Info' %SystemDrive% %SystemRoot%"
)

// build processBuilder using cmd.toArray(new String[cmd.size()]) as a command

The quotes around the cmd /c echo etc are there to prevent the command interpreter to separate arguments. No need to replicate them when you pass raw arguments, and this is what you use with a ProcessBuilder.

Upvotes: 2

Related Questions