Reputation: 447
I have a java application that executes a PowerShell script.
In my java code I read from the the input stream (data that comes from the script) and write to the output stream (data that goes to the script). I also handles the error stream separately.
In the PowerShell script I am using the following command to read from the standard input stream of the script:
$Line = [Console]::ReadLine()
When the script reaches this point in the code it hangs on the ReadLine() till something is written to the stream, that's where the java application comes in.
In java I am writing the following to the output stream (This code is not the entire code but in general and only the important parts of it):
public void runMain()
{
String[] params = "the command and arguments here";
Process process = r.exec(params, null);
outStream = new BufferedOutputStream(process.getOutputStream());
inStream = new BufferedInputStream(process.getInputStream());
errStream = new BufferedInputStream(process.getErrorStream());
startCmd = "some text here\r\n";
wtByte = startCmd.getBytes();
outStream.write(wtByte, 0, wtByte.length);
outStream.flush();
while (!isScriptTerminated && !wasError && !isScriptFinished)
{
if (errStream != null)
{
// handle error
}
if (inStream != null)
{
// read the data from the STDOUT of the script (our input)
readBuffer = receive();
...
}
...
}
}
Has you can see I am writing to the outStream right at the beginning and then I am calling the flush() to actually flush all to the stream, but at this point the script is stuck and hangs on the ReadLine() and my java code reaches the receive() method and waiting for the script to response and write something so standard input, but in this case java code will hang forever because the script is stuck on the ReadLine() forever. Then after a while I have timeout mechanism that kills the process and release the program.
In the experiments that I did I have duplicated the writing to the outStream at the beginning and it sometimes worked and sometimes not. Meaning, the second flush wrote to the stream and script got it.
I must say that I am using the same code to run Perl, VB and Python scripts with no problem.
Moreover, this code is working on my machine (Windows 10) and not working on some other machines like Windows 7, Windows Server 2008. Maybe it has something to do with the PowerShell version?
The question is how come?
What can I do to overcome this problem?
I didn't succeeded to use Read-Host command in PowerShell and I got the same behavior, Is there another way to read in PowerShell script?
Upvotes: 0
Views: 1509
Reputation: 447
It appears that there is a bug in PowerShell version 2.0, once I upgraded to version 3.0 it worked.
On my machine there is version 5.0, that's why it worked on my machine. On the other machines that it didn't work there was version 2.0.
Upvotes: 1