profesorfalken / jPowerShell

Simple Java API to interact with PowerShell console
Apache License 2.0
218 stars 84 forks source link

Get output of powershell script #55

Closed xychen7 closed 5 years ago

xychen7 commented 5 years ago

Hi, I'm trying to execute a powershell script to run psql to create database. I purposely give a invalid IP address to get the error message but getCommandOutput() return nothing although isLastCommandInError () return True . How can I get the actual output of the script ?

My code :

try  {
    PowerShell powerShell = PowerShell.openSession("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
    PowerShellResponse response = powerShell.executeScript("D:\\scripts\\test.ps1",param);

     if (powerShell.isLastCommandInError ()) {
        System.out.print(response.getCommandOutput());
     }   
    System.out.print("Successfully initialize database.");  
}catch (Exception e) {
    System.out.print( e.getMessage());
}

My powershell script :

$output =  & $psql $params -t -A -c "create database $dbName;"  

if  ($LastExitCode -ne 0) {
    $output |Out-File -filepath $log
    write-output "Database initialize incomplete. Please refer to $log for details."
    return "Database initialize incomplete.$output"
}

The error message if I execute the script in powershell :

Database initialize incomplete. Please refer to D:\scripts\201812211503.err for details.
Database initialize incomplete.psql: could not connect to server: Connection timed out (0x0000274C/10060)       
Is the server running on host "10.0.xx.xx" and accepting TCP/IP connections on port 5432?

Any help appreciated.

xychen7 commented 5 years ago

nvm, I turn to processBuilder and it works perfectly. In case anyone face same issue, below is my code :

try  {
    String powershell = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
    String scripts = System.getProperty("user.dir")+"\\scripts\\test.ps1";
    String msg= "";

    ProcessBuilder builder = new ProcessBuilder( powershell, "\""+scripts+" "+param+"\"");
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while (true) {
        line = r.readLine();
        if (line == null)  break; 
        msg = msg+line.trim();
    }
    r.close();
    if (p.exitValue() != 0 )
        System.out.print(msg);
    else System.out.print("Successfully execute script.");
}catch (Exception e) {
    System.out.print(e.getMessage());
}