One approach is to write powershell scripts and have them executed from the program to see the output. Another way is to provide the command directly as string. This way we can create commands dynamically to execute at run-time as required.
Here is the program-
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ExecuteCommand { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String command = "powershell.exe $PSVersionTable.PSVersion"; Process powerShellProcess = Runtime.getRuntime().exec(command); powerShellProcess.getOutputStream().close(); String line; System.out.println("Output:"); BufferedReader stdout = new BufferedReader(new InputStreamReader( powerShellProcess.getInputStream())); while ((line = stdout.readLine()) != null) { System.out.println(line); } stdout.close(); System.out.println("Error:"); BufferedReader stderr = new BufferedReader(new InputStreamReader( powerShellProcess.getErrorStream())); while ((line = stderr.readLine()) != null) { System.out.println(line); } stderr.close(); System.out.println("Done"); } }
It just finds out the powershell version installed on your machine and displays the result on console.
To execute powershell scripts, we just need to have
String command = "powershell.exe \"C:\\PowerShellVersion.ps1\" ";
We need to provide location for the script file to be executed. You can get the source code from here.
Thanks.
Hey can you pls explain the code in detail.. It would be very useful.. Thanks in advance.
ReplyDeleteCan we run those commands in remote server?
ReplyDeletehow can we read the file produced by powershell script by its output through java
ReplyDeleteshja iki mika bura sata kaka
ReplyDeleteYour articles are inventive. I am looking forward to reading the plethora of articles that you have linked here. Thumbs up! PS5Home
ReplyDelete