Java run powershell script
also, if this is Vista/win7/2k8 then you probably cant write to the root of C, so make a temp folder and make that the path.
i dont know java at all, so i cant help you there, but if you do this, you can at least find where the problem is.
Hi Justin, I have modified my.ps1 script to only this set-content c:\test.txt «test» I do not see any output in the console of Eclipse when i run my JAVA code. -Vamsi
that command should create the file, if it does not then you have some other problem and should ask in a java forum.
Hi, It seem the file path may be incorrect. Your file path is » C:/» instead of «c:\», does Jave require this format? If not, the format may be incorrect. Could you place the script file under c:\ directly and test the following? String cmds = (String) «cmd /c powershell c:\MyScript.ps1» If it still not work, create a BAT file which contains: Powershell.exe –file c:\myscript.ps1 Run it manually to make sure it’s working. If it works, change your code to: String cmds «c:\ps.bat» Is there any progress? Thanks. This posting is provided «AS IS» with no warranties, and confers no rights. Please remember to click «Mark as Answer» on the post that helps you, and to click «Unmark as Answer» if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
Hi, I have place my powershell script in the ‘C’ directory. and i have changed my JAVA code as below, but it still doesn’t give any output in my Eclipse Console. import java.io.*; public class PsJava < public static void main( String [] args) throws IOException< Runtime runtime = Runtime.getRuntime(); String cmds = (String) «cmd /c powershell c:/Hello.ps1» ; Process proc = runtime.exec(cmds); proc.getOutputStream().close(); InputStream inputstream = proc.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) < System. out .println(line); > > > Please advice me on this. If I have to create a batch file, then can you let me know how do I do that? Thanks
Hi, Try create a ps.bat file under C:\ which contains: Powershell.exe –file c:\ Hello.ps1 And replace String cmds = (String) «cmd /c powershell c:/Hello.ps1»; With String cmds «c:\ps.bat» What’s the result? If no result, run ps.bat file manually, could it run properly? Thanks. This posting is provided «AS IS» with no warranties, and confers no rights. Please remember to click «Mark as Answer» on the post that helps you, and to click «Unmark as Answer» if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
I know this is an old topic, but just in case someone needs a solution to the problem, I wrestled for a day with it. I’ll post my entire class, but two things are key here. You need feedback on what’s going wrong, and for that you need to read the proc.getErrorStream(). I opt to throw an Exception if the stream contains any data. Next, you need to use -ExecutionPolicy RemoteSigned in the command, or it just won’t work. Hope you find this useful. This is my solution:
package se.brian; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; /** * Operations for executing Windows Powershell Scripts from Java. * * @author Brian Thorne */ public class PowerShellScriptHandler < /** * Executes a Powershell command. * * @param command the command * @return the result as String. * @throws Exception if an error occurs */ public static String executePSCommand(String command) throws Exception < String cmd = "cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive " + command; return exec(cmd); >/** * Executes a Powershell script. * * @param scriptFilename the filename of the script * @param args any arguments to pass to the script * @return the result as String. * @throws Exception if an error occurs */ public static String executePSScript(String scriptFilename, String args) throws Exception < if (!new File(scriptFilename).exists()) throw new Exception("Script file doesn't exist: " + scriptFilename); String cmd = "cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive -file \"" + scriptFilename + "\""; if (args != null && args.length() >0) cmd += " " + args; return exec(cmd); > /** * Executes a batch file. * If you want to call Powershell from the batch file you need to do it using this syntax: * powershell -ExecutionPolicy RemoteSigned -NoProfile -NonInteractive -File c:/temp/script.ps1 * * @param batchFilename the filename of the batch file * @param params any parameters to pass to the batch file * @return the result as String. * @throws Exception if an error occurs */ public static String executeBatchFile(String batchFilename, String params) throws Exception < if (!new File(batchFilename).exists()) throw new Exception("Batch file doesn't exist: " + batchFilename); String cmd = "cmd /c \"" + batchFilename + "\""; if (params != null && params.length() >0) cmd += " " + params; return exec(cmd); > private static String exec(String command) throws Exception StringBuffer sbInput = new StringBuffer(); StringBuffer sbError = new StringBuffer(); Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(command); proc.getOutputStream().close(); InputStream inputstream = proc.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) sbInput.append(line + "\n"); > inputstream = proc.getErrorStream(); inputstreamreader = new InputStreamReader(inputstream); bufferedreader = new BufferedReader(inputstreamreader); while ((line = bufferedreader.readLine()) != null) sbError.append(line + "\n"); > if (sbError.length() > 0) throw new Exception("The command [" + command + "] failed to execute!\n\nResult returned:\n" + sbError.toString()); return "The command [" + command + "] executed successfully!\n\nResult returned:\n" + sbInput.toString(); > >
- Edited by Brian A T Thursday, November 24, 2011 10:43 PM update
- Proposed as answer by Brian A T Friday, November 25, 2011 12:08 AM
Invoke Powershell scripts from Java
I want to invoke my powershell script from java. Can it be done. I tried with the following code, but the stream is not closing.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class TestPowershell < public static void main(String[] args) throws IOException < Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("powershell C:\\testscript.ps1"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); proc.getOutputStream().close(); > >
Does java invoke a powershell script which performs create remote session and execute cmdlets? Do we have support to invoke powershell scripts in java? Anyone could you please help on this. Awaiting for your responses. Thanks, rammj
3 Answers 3
After starting the process ( runtime.exec() ), add a line to close the input stream of the process ( which JAVA calls output stream!!):
Now you can do it easily with jPowerShell
powerShell = PowerShell.openSession(); //Print results System.out.println(powerShell.executeScript("\"C:\\testscript.ps1\"").getCommandOutput()); powerShell.close();
Yes we can create remote session and execute cmdlets using powershell script.
Save the following Power shell script to testscript.ps1
#Constant Variables $Office365AdminUsername="YOUR_USERNAME" $Office365AdminPassword="TOUR_PASSWORD" #Main Function Main < #Remove all existing Powershell sessions Get-PSSession | Remove-PSSession #Encrypt password for transmission to Office365 $SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365AdminPassword -Force #Build credentials object $Office365Credentials = New-Object System.Management.Automation.PSCredential $Office365AdminUsername, $SecureOffice365Password Write-Host : "Credentials object created" #Create remote Powershell session $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $Office365credentials -Authentication Basic –AllowRedirection Write-Host : "Remote session established" #Check for errors if ($Session -eq $null)< Write-Host : "Invalid creditials" >else < Write-Host : "Login success" #Import the session Import-PSSession $Session >#To check folder size Get-MailboxFolderStatistics "YOUR_USER_NAME" | Select Identity, FolderAndSubfolderSize exit > # Start script . Main
try < String command = "powershell.exe \"C:\\testscript.ps1\""; ExecuteWatchdog watchdog = new ExecuteWatchdog(20000); Process powerShellProcess = Runtime.getRuntime().exec(command); if (watchdog != null) < watchdog.start(powerShellProcess); >BufferedReader stdInput = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream())); String line; System.out.println("Output :"); while ((line = stdInput.readLine()) != null) < System.out.println(line); >> catch (Exception e)
If you do not get output, try this: powerShellProcess.getErrorStream() instead powerShellProcess.getInputStream() . It will show the errors.
Executing PowerShell Commands in Java Program
I have a PowerShell Command which I need to execute using Java program. Can somebody guide me how to do this? My command is Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
Yes,I have gone through that question but can you give me a basic examle to set me going? I want to learn this.
You need to exercise your google-fu and look up some examples. There’s no reason you can’t at least make an attempt at researching this.
4 Answers 4
You should write a java program like this, here is a sample based on Nirman’s Tech Blog, the basic idea is to execute the command calling the PowerShell process like this:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PowerShellCommand < public static void main(String[] args) throws IOException < //String command = "powershell.exe your command"; //Getting the version String command = "powershell.exe $PSVersionTable.PSVersion"; // Executing the command Process powerShellProcess = Runtime.getRuntime().exec(command); // Getting the results powerShellProcess.getOutputStream().close(); String line; System.out.println("Standard Output:"); BufferedReader stdout = new BufferedReader(new InputStreamReader( powerShellProcess.getInputStream())); while ((line = stdout.readLine()) != null) < System.out.println(line); >stdout.close(); System.out.println("Standard Error:"); BufferedReader stderr = new BufferedReader(new InputStreamReader( powerShellProcess.getErrorStream())); while ((line = stderr.readLine()) != null) < System.out.println(line); >stderr.close(); System.out.println("Done"); > >
In order to execute a powershell script
String command = "powershell.exe \"C:\\Pathtofile\\script.ps\" ";