Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoke background command on remote machine

I'd like to spawn a process on a remote host from a powershell script and have that process continue to run after the local script has exited. The remote command is the vmrun.exe program that comes with VMware Workstation, which starts up a VM and exits immediately.

The behavior that I'm seeing is that the vmware processes are killed as soon as the remote session ends with the script. I'd like the processes to keep running. This is what I'm using so far:

function Start-VM {
    param( [String] $vmwareDir, [String] $vmDir, [String] $vm )
    [String] $command = "& `"$vmwareDir\vmrun.exe`" start `"$vmDir\$vm`" nogui"
    Invoke-Expression $command
}

[String] $hostname = "myhost.fqdn"
[String] $vmwareDir = "C:\Program Files (x86)\VMware\VMware Workstation"
[String] $vmDir = "C:\Path\To\VM"
[String] $vm = "my vm.vmx"

$session = New-PSSession -ComputerName $hostname
Invoke-Command -Session $session -AsJob -ScriptBlock ${function:Start-VM} -ArgumentList $vmwareDir, $vmDir, $vm
if( !$? ){
    Write-Host "Failed to start VM"
    exit
}
sleep 60

With this code, the VM is started on myhost.fqdn and runs until the 60 second sleep ends, after which it's killed along with the local script. I'm only creating a PSSession object in this case as a proof of concept that the remote process only lives as long as the session.

Thanks in advance!

EDIT:

If it helps to clarify what I'd like to do, the functional equivalent in Linux would be something like:

ssh myhost.fqdn "nohup my-command &>/dev/null &"
like image 215
Christopher Neylan Avatar asked Mar 06 '26 02:03

Christopher Neylan


1 Answers

In this answer, I analyse the problem and give a workaround (see edited at the end). I not sure that your question is really a duplicate.

like image 153
JPBlanc Avatar answered Mar 07 '26 21:03

JPBlanc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!