Crear, compilar y ejecutar una clase de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import java.io.*; public class CrearJava { public static void main(String[] args) { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("EjecutarPowerShell.java"); pw = new PrintWriter(fichero); pw.println("import java.io.IOException;"); pw.println("import java.io.BufferedReader;"); pw.println("import java.io.IOException;"); pw.println("import java.io.InputStreamReader;"); pw.println("public class EjecutarPowerShell"); pw.println("{"); pw.println(" public static void main(String[] args) throws InterruptedException"); pw.println(" { "); pw.println(" Runtime runtime = Runtime.getRuntime();"); pw.println(" try"); pw.println(" {"); pw.println(" Process process = runtime.exec(\"powershell.exe $PSVersionTable.PSVersion\");"); pw.println(" "); pw.println(" process.getOutputStream().close();"); pw.println(" String line;"); pw.println(" BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));"); pw.println(" while ((line = stdout.readLine()) != null){"); pw.println(" System.out.println(line);"); pw.println(" }"); pw.println(" }"); pw.println(" catch(IOException ex){"); pw.println(" System.exit(-1);"); pw.println(" }"); pw.println(" }"); pw.println("}"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fichero) fichero.close(); } catch (Exception e2) { e2.printStackTrace(); } } //Compilar y ejecutar el fichero creado EjecutarPowerShell.java Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("javac EjecutarPowerShell.java"); process.getOutputStream().close(); String line; BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = stdout.readLine()) != null){ System.out.println(line); } Process process2 = runtime.exec("java EjecutarPowerShell"); process2.getOutputStream().close(); String line2; BufferedReader stdout2 = new BufferedReader(new InputStreamReader(process2.getInputStream())); while ((line2 = stdout2.readLine()) != null){ System.out.println(line2); } } catch(IOException ex){ System.err.println("Error"); System.exit(-1); } } } |