在远程计算机上运行命令

我想在使用C#的远程计算机上的命令提示符下运行命令。 根据此链接如何在远程计算机中执行命令? ,我试图使用以下代码执行此操作:

public static void RunRemoteCommand(string command, string RemoteMachineName) { ManagementScope WMIscope = new ManagementScope( String.Format("\\\\{0}\\root\\cimv2", RemoteMachineName)); WMIscope.Connect(); ManagementClass WMIprocess = new ManagementClass( WMIscope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); object[] process = { command }; object result = WMIprocess.InvokeMethod("Create", process); Log.Comment("Creation of process returned: " + result); } 

这将返回退出代码0并且不会抛出任何错误,但不会执行任何操作。 请帮忙。

希望这会有所帮助

http://www.petri.co.il/command-line-wmi-part-2.htm

请查看“备用凭据”部分。 我相信你能够自己做一些修改。

如果你愿意尝试一下, psexec对于这类事情很有用。

我知道这篇文章很老但是对于遇到这个页面的人来说也是完整的:RRUZ的评论是正确的,但是为了在远程机器上运行,还有一件事可能需要。 为此,您需要添加连接选项:

 public static void RunRemoteCommand(string command, string RemoteMachineName, string username,string password) { var connection = new ConnectionOptions(); connection.Username = username; connection.Password = password; ManagementScope WMIscope = new ManagementScope( String.Format("\\\\{0}\\root\\cimv2", RemoteMachineName), connection); WMIscope.Connect(); ManagementClass WMIprocess = new ManagementClass( WMIscope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); object[] process = { command }; object result = WMIprocess.InvokeMethod("Create", process); Log.Comment("Creation of process returned: " + result); }