Código del script en PowerShell (guardar como ejecutar.ps1)
1 |
echo "hola" |
Código en Java para ejecutar el script
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 |
import java.io.IOException; import java.util.concurrent.TimeUnit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProcesoPowerShell { public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("powershell.exe C:\\Users\\juan\\Desktop\\ejecutar.ps1"); process.getOutputStream().close(); String line; BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = stdout.readLine()) != null){ System.out.println(line); } TimeUnit.SECONDS.sleep(2); } catch(IOException ex){ System.err.println("Error"); System.exit(-1); } } } |
Resultado de la ejecución