0

I have a java code that execute a powershell script.My parameters are in a string array that I got from user.

String sentence = clientinp.readUTF();
            String[] parts = sentence.split(",");

How should I put the parameters to the script every time I execute the code? I tried this code:

String command = "powershell.exe  $Add-DnsServerResourceRecordA -ZoneName -Name -IPv4Address -TimeToLive";

But I don't know how can I pass this array to powershell.What should I do?

Navita Saini
  • 362
  • 3
  • 12
sara
  • 3
  • 5
  • If you have made sure that the input parameters are in the exact order you need them you can simply ask for the elements to do stuff like `"powershell.exe $Add-DnsServerResourceRecordA" + parts[0] +" ... " + parts[...];` – px06 Nov 21 '16 at 11:11
  • [link] http://stackoverflow.com/questions/29545611/executing-powershell-commands-in-java-program <- this will help you – Onkar Nov 21 '16 at 11:17
  • @px06 yes I'm sure.i should try this: "powershell.exe $Add-DnsServerResourceRecordA + parts[0] + parts[1]" ; without " end of $Add-DnsServerResourceRecordA" ? – sara Nov 21 '16 at 11:20
  • @px06 I wrote ("powershell.exe $Add-DnsServerResourceRecordA + parts[0] + parts[1]") or ("powershell.exe $Add-DnsServerResourceRecordA + 'parts[0]' + 'parts[1]' " ) but i have ioexeption – sara Nov 21 '16 at 11:27
  • @Onkar I used this.now when i execute the powershell I want to pass my array instead of enter the value myself : String command = "powershell.exe $Add-DnsServerResourceRecordA -ZoneName -Name -IPv4Address -TimeToLive"; – sara Nov 21 '16 at 11:34
  • Combine your array as one string by seperating comma(,) and then execute – Onkar Nov 21 '16 at 13:02
  • @Onkar "powershell.exe Add-DnsServerPrimaryZone -Name ' zoneName ' -ZoneFile 'zoneFileName' " zone name and zone file are in my string array and i want to put them in this script.what should i do? – sara Nov 21 '16 at 13:33
  • Yes You can use ProcessBuilder refer fireandfuel answer – Onkar Nov 21 '16 at 17:13

1 Answers1

0

Use a ProcessBuilder. You have to put each parameter (including path to the program) as items to an array or list and pass it to the constructor of ProcessBuilder.

for example:

String[] arguments = {"powershell.exe", "$Add-DnsServerResourceRecordA", "-ZoneName", "[your zone name]", "-Name", "[your name]", "-IPv4Address", "[your ipv4 address]", "-TimeToLive", "[your TTL]"};
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
Process process = processBuilder.start();

As an alternative you can use Runtime.getRuntime().exec()

fireandfuel
  • 732
  • 1
  • 9
  • 22