Reputation: 184
Ugh powershell...
Ok I've been reading a lot of other answer but none of them work.
What I want to do is have a powershell script that will open a jar or open a jar with a argument. This should be so simple but I can't figure out the correct way do this easily with the powershell documentation from Microsoft...
runprogram.ps1
#Pseudocode
$PathToApp = "C:\App"
IF $PathToApp exist THEN
IF no additional argument THEN
goto PathToApp
Start-Process java -jar app.jar
ELSE IF additional argument THEN
goto PathToApp
Start-Process java -jar app.jar $arg
ENDIF
ELSE
print("Error path to app not set...")
ENDIF
then I should be able to wrtie ./runprogram.ps1 or ./runprogram.ps1 file.txt
Based on other stackoverflow post I'm sure a simple answer to this would help not only myself but many others.
Thank you for reading. And even if you don't provide a simple way to do this could you point me to some good similar examples that I could peace together. Since I and I'm sure others find powershell to be cumbersome to learn to do a simple task like this...
EDIT: In case anyone ever finds this post in the future here is something that works I made.
param(
[string]$OpenFile
)
$AppPath = "C:\App.jar"
#Check if path exist
if (-not(Test-Path $AppPath)) {
write-error "Path to app not found..."
} else {
if(-not($OpenFile)) {
Start-Process -FilePath java.exe -ArgumentList "-jar $AppPath"
} else {
Start-Process -FilePath java.exe -ArgumentList "-jar $AppPath $OpenFile"
}
}
I hope this helps someone else.
Upvotes: 1
Views: 4521
Reputation: 2846
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
Let me know if need all the steps for apache-commons-daemon windows service as well.
Upvotes: 1