Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 831
Rammj Avatar asked Nov 16 '11 06:11

Rammj


People also ask

How do I launch a PowerShell script?

In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

How do I run a PowerShell script from a PowerShell script?

To open the PowerShell console, click on the Start button (or search button), type powershell, and click Run as Administrator. To run a script in the PowerShell console, you can either: Use the full path to script, like: C:\TEMP\MyNotepadScript. ps1.

Can GPO run PowerShell script?

You can use GPOs not only to run classic batch logon scripts on domain computers ( . bat , . cmd , . vbs ), but also to execute PowerShell scripts ( .

What is PowerShell in Java?

It is both a scripting language and a command-line Shell. It can interact with a different number of technologies. Windows PowerShell allows complete access to all the types in the . NET framework. PowerShell is object-based.


2 Answers

After starting the process ( runtime.exec() ), add a line to close the input stream of the process ( which JAVA calls output stream!!):

 proc.getOutputStream().close();
like image 68
manojlds Avatar answered Oct 09 '22 06:10

manojlds


Now you can do it easily with jPowerShell

powerShell = PowerShell.openSession();

//Print results    
System.out.println(powerShell.executeScript("\"C:\\testscript.ps1\"").getCommandOutput());

powerShell.close();
like image 30
profesor_falken Avatar answered Oct 09 '22 06:10

profesor_falken