profesorfalken / jPowerShell

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

Commands With No Output Always Timeout #11

Open michael-hay opened 8 years ago

michael-hay commented 8 years ago

If you run a command that does not return any output we will sit and poll expecting an output till we hit the timeout.

String serverName = new String("remoteServer");
Sting cmd = new String("Remove-Item "E:\temp\*" -recurse");

    private static String executePowerShellCmd(PowerShell powerShell, String cmd, String timeout) throws InterruptedException {
        printCmd(cmd);
        Map<String, String> myConfig = new HashMap<>();
        myConfig.put("maxWait", timeout);
        PowerShellResponse response = powerShell.configuration(myConfig).executeCommand(cmd);
        return response.getCommandOutput();
    }

    public static void executeRemoteCmd(String cmd, String automationHome, String serverName, String timeout) throws Exception {
        PowerShell powerShell = null;
        try {
            powerShell = PowerShell.openSession();
            System.out.println(executePowerShellCmd(powerShell, "Invoke-Command -ComputerName " + serverName + " {" + cmd + "}", timeout));
        } catch(PowerShellNotAvailableException ex) {
            throw new RuntimeException("Failed to run PowerShell", ex);
        } finally {
            if (powerShell != null)
                 powerShell.close();
        }
    }
profesorfalken commented 8 years ago

Hello,

Yes, this is related with the previous issue. As we do not handle the return code of the process we cannot see if it finish if it does not return anything. That happens in your case because you are launching a command to a remote server.

I will see if I can do something similar to what I did in issue #8. I guess I could create a temp script for each command and append a return string to this script. In that case I will be able to guarantee that there is always an output.

michael-hay commented 8 years ago

A good test command for this is:

Invoke-Command -ComputerName serverName {(Get-Service serviceName).WaitForStatus('Running','02:00:00')}

Thx very much. These classes are quite useful.

profesorfalken commented 8 years ago

Hi,

If you use the v1.7 you should have no problem. You only have to enable the remote mode.

Map<String, String> myConfig = new HashMap<>();
myConfig.put("remoteMode", "true");
response = powerShell.configure(myConfig).executeCommand("Invoke-Command -ComputerName serverName {(Get-Service serviceName).WaitForStatus('Running','02:00:00')}");

Best regards

Tuupertunut commented 6 years ago

Is there any situation where you wouldn't want to use remote mode?