I am working on a piece where I have to start an application and this application should be keep running in background. I tried Start-Process cmdlet as below:
try {
Invoke-Command -Session $newsession -Scriptblock {
Write-Host "Cd'ing and starting Vesper on" $loadvm
Start-Process cmd -ArgumentList "/c C:\vesper_cpt\Vesper.exe -auto" -verb runas
} -ErrorAction Stop
} catch [Exception] {
echo "Error while running the remote command", $_.Exception.GetType().FullName, $_.Exception.Message
Remove-PSSession $newsession
exit 1
}
Remove-PSSession $newsession
What is happening is that I can see that it starts a cmd process on the target machine but then it immediately goes away. I am not sure what should I do here to have that process up and running always. On the other hand, I also tried Invoke-Expression cmdlet and with this I can see the process has started fine on the remote machine but the powershell script never returns and that is why thought of using Start-Process. Any suggestions?
After trying so many things like Invoke-Expression, Start-Process, I found the reason of why my process was exiting just after it starts on remote-machine. The reason is that the application which I am running is a Java application. And, JVM does not allow a daemon thread to run the process on the machine. On the other hand, if at least one user thread is alive, the Java runtime won't terminate your application.
In my setup, I am running the application on remote machine(in this case Vesper.exe) so I was creating a New-PSSession and then in the end, I was Removing-PSSession. Because of that, there was no user thread left to run the application and because of that the application was closing.
The solution to this is instead of Removing-PSSession, you are going to do Exit-PSSession. Exit-PSSession, keeps the thread alive and your application does not terminate. Take care of the face that, it would be your responsibility of how you are going to exit the application because even if your program is finished the application would still be running on remote machine.
try {
Invoke-Command -Session $newsession -Scriptblock {
Write-Host "Cd'ing and starting Vesper on" $loadvm
Start-Process cmd -ArgumentList "/c C:\vesper_cpt\Vesper.exe -auto" -verb runas
} -ErrorAction Stop
} catch [Exception] {
echo "Error while running the remote command", $_.Exception.GetType().FullName, $_.Exception.Message
Remove-PSSession $newsession
exit 1
}
Exit-PSSession
This is upto you what you want to do if exception get caught. You can Remove or Exit Session as per your environment setup.
I found the answers from following two questions:
Hope this helps.
Thanks