2

I'm connecting to windows machine using ssh and trying to execute command to run in the background. Running the following command from the terminal after ssh established works:

start PowerShell.exe -ExecutionPolicy Unrestricted Invoke-Command -ScriptBlock{"cd C:\Users\myuser\AppData\Roaming\npm\node_modules\myserver\; npm start > log.log 2>&1"}

But what I really need is to run the following command and it doesn't work:

ssh myuser@machine_ip "start PowerShell.exe -ExecutionPolicy Unrestricted Invoke-Command -ScriptBlock{\"cd C:\Users\myuser\AppData\Roaming\npm\node_modules\myserver\; npm start > log.log 2>&1\"}"

Running the second command without 'start' works but it 'holds' the terminal. And basically it's not a must to work with powershell if someone can tell how to execute the below command and make it run in the background: cd C:\Users\myuser\AppData\Roaming\npm\node_modules\myserver\; npm start > log.log 2>&1

thanks

TomerG
  • 21
  • 2
  • Take a look at the Start-Job cmdlet. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/start-job?view=powershell-5.1 – Peter the Automator Nov 10 '21 at 14:17
  • Why use invoke-command or powershell at all? – js2010 Nov 10 '21 at 14:35
  • js2010, it's not mandatory at all, but this is the way I got to send the commands. I've found a way to bypass this with 'bat' script and psexec, but it also stack the terminal for example: ssh myuser@machineIp psexec myscript.bat -d – TomerG Nov 10 '21 at 15:52
  • @js2010 see my comment above – TomerG Nov 11 '21 at 06:42
  • finally found how it works and the solution - https://stackoverflow.com/questions/8675847/launching-background-tasks-in-a-remote-session-that-dont-get-killed-when-the-se/8704945#8704945 – TomerG Nov 11 '21 at 10:56

1 Answers1

0

I can't test this piece of code, but Invoke-Command has a command called -asjob.

ssh myuser@machine_ip "start PowerShell.exe -ExecutionPolicy Unrestricted Invoke-Command -ScriptBlock{\"cd C:\Users\myuser\AppData\Roaming\npm\node_modules\myserver\; npm start > log.log 2>&1\"}" -AsJob

Microsoft documentation: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-5.1#example-8--run-a-background-job-on-several-remote-computers