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

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can also modify you script to expect a command line argument and pass it while calling from java
thank you heaps! this works. big thank you - appreciate your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.