How can I launch .cmd files on a remote machine?

核能气质少年 提交于 2019-12-22 11:05:09

问题


I need to be able to launch a .cmd file that is on a remote machine, from within the directory that the file resides on that machine.

I've tried: invoke-command -ComputerName test123 -ScriptBlock { cmd /c c:/myfile.cmd } in powershell, which launches the .cmd, but then fails because it can't find the corresponding .cmds that this one launches (which all reside in the same directory).

Is there a way to launch this .cmd file, and have it's execution persist? i.e., even after the powershell window is closed, the .cmd will continue to run on the remote machine.


回答1:


You need to change the working directory in the scriptblock. Add a Set-Location before calling the batch script:

Invoke-Command -ComputerName test123 -ScriptBlock {
  Set-Location 'C:\'
  & cmd /c ".\myfile.cmd"
}

If you need to create a detached process, you can do that for instance via WMI:

$hostname = 'test123'
$command  = 'C:\path\to\script.cmd'
$workdir  = 'C:\working\directory'

$p = [wmiclass]"\\$hostname\root\cimv2:Win32_Process"
$p.Create($command, $workdir)

Note that you need admin privileges on the remote host for this.



来源:https://stackoverflow.com/questions/23091731/how-can-i-launch-cmd-files-on-a-remote-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!