3

i have used this example to be able to run a script through a java program to simply get a text output (it works as required).

  String command = "powershell.exe  \"C:\\Users\\--\\--\\script.ps1\" ";
  Process powerShellProcess = Runtime.getRuntime().exec(command);

i am looking at furthering my script within java to use said script on multiple pages, with the only change being an address variable ideally passed through from a loop within eclipse. i have $address variable in my script.ps1 file where it is currently declared at the top of my powershell script - ideally i want to be able to declare $address in eclipse.

Is this possible? or would i need to adjust the script another way.

Thank you

Joshfromnz
  • 45
  • 4

1 Answers1

1

You can set the variable using Runtime.exec, but you'll have to do it in the same command, otherwise the script will lose the context, because it will run in a different powershell that does not know the variable.

So, in one command you Set-Variable (or SET for cmd, or EXPORT for linux) and call your ps1 script (or in my case, echo):

String myvar = "TextTextText";

final Runtime rt = Runtime.getRuntime();
String[] commands = {"powershell.exe", "Set-Variable", "-Name \"myvar\" -Value \""+myvar+"\";", "echo $myvar"};

Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

String s = null;

while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}
res
  • 775
  • 8
  • 16