I am using Rhino and I have the following function which calls PowerShell, compares two text files and saves the difference to a text file.
function RunPowerShell()
{
var CommandPS= ' $File1 = Get-Content "C:\\Test\\test1.txt"; $File2= Get-Content "C:\\Test\\test2";Compare-Object $File1 $File2 -PassThru >"C:\\Test\\Results.txt"';
println(CommandPS);
var CmdCommand= 'cmd /c PowerShell '+ CommandPS;
var CmdResults= new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.Runtime.getRuntime().exec(CmdCommand).getErrorStream()));
CmdResults.close();
}
RunPowerShell();
The function works just fine; the file Results.txt is created but I cannot delete it because is saying is in use.
I am closing the BufferedReader at the end but i still cannot delete the file unless I kill the process from task manager.
Thanks in advance,
Runtime.exec()
does not block: it forks a process that runs asynchronously. So you are probably reaching the end of your script before the process has terminated.
I'm not sure why you need to kill the process to exit, but my guess is that you need to consume some input from PowerShell's output. So I'd try two things:
Get the process object and wait for it to complete.
var process = java.lang.Runtime.getRuntime().exec(CmdCommand);
var exitCode = process.waitFor(); // blocks until process completes
If that alone does not work, issue an exit at the end of your script:
java.lang.System.exit(0);
There are two other approaches you could use that would involve larger changes but would help you if you're going to build on this.
You could use java.lang.ProcessBuilder
, which is a more convenient API for dealing with processes, introduced in a later version of Java (but undoubtedly still included in what you're running).
You could use Rhino's runCommand
which is intended to do this sort of thing. I've found it to be a tiny bit buggy but it works great for most cases. See Mozilla's Rhino shell documentation.