Run a remote command in background

I have Win PC run PS connects a device running ubuntu.
I could remotely ssh to ubuntu and run a command. for example,
plink -batch -ssh root@12.34.56.78 -pw 1234 touch x.txt
remote device will run “touch x.txt” and I can see x.txt is generated on remote device.
when I try to make above command run as background by doing this
Start-Job -ScriptBlock{plink -batch -ssh root@12.34.56.78 -pw 1234 touch x.txt}

the x.txt is not generated on remote device.

What have I missed? please help.
thanks
c-xian

Start-Job -ScriptBlock {
    Start-Process -FilePath plink -ArgumentList '-batch -ssh root@$12.34.56.78 -pw 1234 touch x.txt'
} -Name plinktest
2 Likes

Wow! it works great! you are expert. thank you so much.
more Questions:

  1. when I use $ip=“12.34.56.78” and replace “-ssh root@12.34.56.78” with “-ssh root@$ip” it failed to work. how could I change the remote device ip address as a variable?
  2. how could I get remote command console output redirects to a file of win PC?

very much appreciated.
c-xian

Receive-Job should get results of the job; but if not, the redirect parameter will work.

Start-Job -ScriptBlock {
    $ip=“12.34.56.78”
    Start-Process -FilePath plink -ArgumentList "-batch -ssh root@$ip -pw 1234 touch x.txt" -RedirectStandardOutput C:\plinkout1.txt
} -Name plinktest

$result = Get-Job -Name plinktest | Receive-Job
$result | Out-File C:\plinkout2.txt

mmm, it doesn’t work.

  1. I need $ip change outside ScriptBlock{ … }

thanks
c-xian

I figured out $ip issue. $ip is not visible in -ScriptBlock{}. in order to make it visible. use $env:ip instead.
still did not figure out the remote console output to host PC yet.