I'm running a jar from powershell using Invoke-Expression:
$line="c:\temp\my file.txt"
$cmd="java -jar C:\temp\post.jar `"" + $line + "`""
invoke-expression $cmd
If I test $? it will only give me the status of Invoke-Expression which will always be a success as the java executable and post.jar can be found.
Also, I've thought of running the java program directly and test $? but sometimes the file name can be very complex and sometimes I put extra options.
How do I get the status of the run of the post.jar program?
Thanks.
You could try to check the exit code of the process via:
$p = Start-Process java -ArgumentList '-jar C:\temp\post.jar',$file -Wait -PassThru
$p.ExitCode
Based on -PassThru you'll receive a System.Diagnostics.Process-object that should include the exit-code of the jar. For more info see the Start-Process cmdlet description.
Hope that helps.
Related
I'm trying to write a PowerShell script to update Spigot using Git Bash. Hopefully from the two failed PS examples below you get the gist of what I'm trying to do.
I can successfully open a Git Bash shell in the target folder and run java -jar BuildTools.jar. When I try to run through PowerShell, a CMD window opens and immediately closes. No errors are displayed and best I can tell, the CMD window contains no text. I prefer to use PowerShell over a CMD script because I am leveraging Invoke-WebRequest earlier on to get the latest version of BuildTools.jar. I would like to keep all this together in one script.
Example 1:
Start-Process -FilePath "C:\Program Files\Git\bin\bash.exe" -ArgumentList "--login -i -c ""java -jar BuildTools.jar"""
Example 2:
Start-Process -FilePath "C:\Program Files\Git\bin\bash.exe" -ArgumentList '--login', '-i', '-c', '"java -jar BuildTools.jar"'
Figured it out thanks to an idea from Ansgar Wiechers.
Solution is as follows:
Start-Process -FilePath "C:\Program Files\Git\bin\bash.exe" -ArgumentList '-c', '"cd /c/Bitnami/Updater && java -jar BuildTools.jar"'
I have a powershell script that is calling a jar via the following code:
Start-Process java -ArgumentList '-jar', "$jarPath", "$csvPath"
However, the output from the jar is not coming through. I'm pretty sure its running successfully, but I'd like to be sure. How can I pass it through to the Powershell console?
Replace Start-Process with the call operator:
& java -jar $jarPath $csvPath
This works fine for me:
$stdout = "C:\temp\stdout.txt"
Start-Process powershell -ArgumentList "echo 123" -RedirectStandardOutput $stdout -Wait
$output = Get-Content $stdout
echo $output
Remove-Item $stdout
Since I started Powershell process with command echo 123, it returned 123to stdout, so this value is saved to file.
Swap Powershell with Java and it should be working as you expect.
Remember, that you cannot redirect stdout directly to variable, you must do it via file.
I am trying to execute a powershell script from my java console app, I was able to get this working with the below command:
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd "+dir+" & start cmd.exe /k \"Powershell C:\\runscript.ps1 args\"",null,dir);
p.waitFor();
Inside my powershell script, i have the below snippet which gets called in a loop,
Start-Process -FilePath $RunLocation -ArgumentList $args -wait -NoNewWindow -RedirectStandardOutput $OutputFile
$output = Get-Content $OutputFile| out-string
if(!($output.toLower().contains("failed"){
Remove-Item $outLogFile
}
If I open command prompt, and copy exactly what I have in my exec(...) command, it runs great, however, when I run it in my Java application, it seems like the -wait in my powershell script is being ignored, and the next line (which is checking and removing logs) is run, I've even gone to the length of adding a sleep for a few seconds in my powershell just after the Start-Process, this works but I'm hoping there is a better way.
The error i am getting is in the powershell script is below (this only happens when ive run it from my Java app, the -wait waits foor the start process to finsih before continuing when run directly from command prompt..):
Remove-Item : Cannot remove item D:\adhoc\logs\2016-06\output38844448.out: The process cannot access the file
'D:\adhoc\logs\2016-06\output38844448.out' because it is being used by another process.
At C:\runscript.ps1:91 char:3
+ Remove-Item $OutputFile
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:\adhoc\log...4448.out:FileInfo) [Remove-Item], IOException
+ FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
Why is the -wait in my powershell script not working when I run it from my Java app using runtime().exec?
I need to call a java program (jar file )from PowerShell.
The following code works:
java -jar $cls --js $dcn --js_output_file $dco
But I need to have to run the app in a process (using Start-Process).
I am trying the following with no sucess:
Start-Process -FilePath java -jar $cls --js $dcn --js_output_file $dco -wait -windowstyle Normal
Error:
Start-Process : A parameter cannot be found that matches parameter name 'jar'.
Any idea how to fix it?
You will need to use following format for powershell:
Start-Process java -ArgumentList '-jar', 'MyProgram.jar' `
-RedirectStandardOutput '.\console.out' -RedirectStandardError '.\console.err'
Or other option you can use is Start-job:
Start-Job -ScriptBlock {
& java -jar MyProgram.jar >console.out 2>console.err
}
It looks like the -jar is being picked up as an argument of Start-Process rather than being passed through to java.
Although the documentation states that -ArgumentList is optional, I suspect that doesn't count for -option-type things.
You probably need to use:
Start-Process -FilePath java -ArgumentList ...
For example, in Powershell ISE, the following line brings up the Java help (albeit quickly disappearing):
Start-Process -FilePath java -argumentlist -help
but this line:
Start-Process -FilePath java -help
causes Powershell itself to complain about the -help.
Option 1 [Using Start-Job ScriptBlock]
Start-Job -ScriptBlock {
& java -cp .\Runner.jar com.abc.bcd.Runner.java >console.out 2>console.err
}
if ( $? == "True")
write-host("Agent started successfully")
else if ($? == "False")
write-host("Agent did not start")
Option 2 [Using Start-Process]
Start-Process -FilePath '.\jre\bin\java' -WindowStyle Hidden -Wait -ArgumentList "-cp .\Runner.jar com.abc.bcd.Runner"
That's how i did it using above two options initially.
Option 3 [Using apache-commons-daemon]
I can suggest a better and robust alternative.
You can use apache-commons-daemon library to build a windows service for your java application and then start, stop the service very conveniently.
There is amazing youtube video which will explain apache commons daemon and how to build a windows service. I will attach the reference at the end.
References :
https://commons.apache.org/proper/commons-daemon/index.html
https://www.youtube.com/watch?v=7NjdTlriM1g
So I created a script the the following commands
#! /usr/bin/sh
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
JAVA=/usr/bin/java
MY_SERVER=/home/user/Desktop/Hello.jar
USER=user
/bin/su - $USER -c "$JAVA -jar $MY_SERVER &"
And I saved it in
etc/init.d/
And then ran the following command in terminal
sudo update-rc.d java_server_launch.sh defaults
I have a program located at
/home/user/Desktop/
And it is called Hello.jar and it works fine when I run it. When I restart my computer for some reason the program (Hello.jar) does not execute. What am I doing wrong?
I'm doing exactly what the answer here says.
You need to replace Hello.jar with $MY_SERVER in the last line of your bash script. That's because your current working directory isn't /home/user/Desktop
Edit: Try replacing the last line of code with this:
/bin/su $USER -c "$JAVA -jar $MY_SERVER &"
if you're running on Ubuntu you should check out upstart
see how simple it is to run jar https://stackoverflow.com/a/12102542/41576