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 78 79 80 81 82 83 84 85 |
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 crear un fichero JAR que 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("jar cf EjecutarPowerShell EjecutarPowerShell.class"); process2.getOutputStream().close(); String line2; BufferedReader stdout2 = new BufferedReader(new InputStreamReader(process2.getInputStream())); while ((line2 = stdout2.readLine()) != null){ System.out.println(line2); } Process process3 = runtime.exec("java EjecutarPowerShell"); process3.getOutputStream().close(); String line3; BufferedReader stdout3 = new BufferedReader(new InputStreamReader(process3.getInputStream())); while ((line3 = stdout3.readLine()) != null){ System.out.println(line3); } } catch(IOException ex){ System.err.println("Error"); System.exit(-1); } } } |