Note that there are some explanatory texts on larger screens.

plurals
  1. POExecute batch files from JAVA and capture batch environment
    primarykey
    data
    text
    <p>I need a solution that allows to capture the batch file exit code and the resultant environment - by this I mean that I need to retrieve the system environment + variables set within the batch.</p> <p>For better understanding here is what I came up with. Unfortunately the printEnvironment() method does not print out the variable MyVar set previously in batch but only the system variables. Is there a way to capture "MyVar" without changeing the batch file itself?</p> <pre><code>import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; class Main{ public static void main(String[] args){ String command = "C:/temp/varTest.bat"; MyTask mt = new MyTask(command); mt.run(); } } class MyTask implements Runnable{ private ProcessBuilder pb; private Process process; private int exitCode; private Map&lt;String, String&gt; env; private String command; public MyTask(String command){ this.command = command; } public void run(){ try { pb = new ProcessBuilder(command); process = pb.start(); process.waitFor(); exitCode = process.exitValue(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally{ System.out.println("Execution finished! Exit code: " + exitCode); printEnvironment(); process.destroy(); } } private void printEnvironment(){ env = pb.environment(); List&lt;String&gt; envKeys = new ArrayList&lt;String&gt;(env.keySet()); Collections.sort(envKeys); for(String key : envKeys){ System.out.println(key+" ==&gt; "+env.get(key)); } } } </code></pre> <p>The batch file code:</p> <pre><code>set MyVar=VAL </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload