使用WMI在远程计算机中执行进程

时间:2013-10-28 08:24:48

标签: c# process wmi wmi-query

我想打开进程pon远程机器,这个远程机器在本地网络内部。 我尝试这个命令,并且在远程机器上没有任何反应,我连接的这个用户拥有管理员权限。 这两台机器都运行Windows 7

static void Main(string[] args)
{
    try
    {
        //Assign the name of the process you want to kill on the remote machine
        string processName = "notepad.exe";

        //Assign the user name and password of the account to ConnectionOptions object
        //which have administrative privilege on the remote machine.
        ConnectionOptions connectoptions = new ConnectionOptions();
        connectoptions.Username = @"MyDomain\MyUser";
        connectoptions.Password = "12345678";

        //IP Address of the remote machine
        string ipAddress = "192.168.0.100";
        ManagementScope scope = new ManagementScope(@"\\" + ipAddress + @"\root\cimv2", connectoptions);

        //Define the WMI query to be executed on the remote machine
        SelectQuery query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
        object[] methodArgs = { "notepad.exe", null, null, 0 };
        using (ManagementObjectSearcher searcher = new
                    ManagementObjectSearcher(scope, query))
        {
            foreach (ManagementObject process in searcher.Get())
            {
                //process.InvokeMethod("Terminate", null);
                process.InvokeMethod("Create", methodArgs);
            }
        }

        Console.ReadLine();

    }
    catch (Exception ex)
    {
        //Log exception in exception log.
        //Logger.WriteEntry(ex.StackTrace);
        Console.WriteLine(ex.StackTrace);

    }
}

2 个答案:

答案 0 :(得分:2)

您没有使用该代码打开进程,但是您正在枚举名为"iexplore.exe"的所有正在运行的进程并将其关闭。

我认为更简单,更好的方法是使用SysInternals PsExecTask Scheduler API

如果您想使用WMI,您的代码应如下所示:

object theProcessToRun = { "YourFileHere" };

ManagementClass theClass = new ManagementClass(@"\\server\root\cimv2:Win32_Process");

theClass.InvokeMethod("Create", theProcessToRun);

----------回复你的评论------------------

首先,您需要改变您的态度和编码方法,并阅读您复制/粘贴的代码。

然后你应该学习更多关于编程语言的知识。

不,我不会为你编写代码。我给了你一个指示正确方向的提示。现在轮到你发展它了。玩得开心!!

答案 1 :(得分:-1)

这是我在使用vbs脚本之前为我的公司所做的脚本。可以搜索网络将其转换为C#等。步骤的基本原理以及如何使用WMI启动服务。有一个很好的编码,玩得开心。

sUser = "TESTDomain\T-CL-S"
sPass = "Temp1234"  

Set ServiceSet = GetObject("winmgmts:").ExecQuery("Select * from Win32_Service where Name = 'netlogon'")

For Each Service In ServiceSet
   Service.StopService
   Service.Change "netlogon",Service.PathName, , ,"Automatic",false,sUser,sPass
   Service.StartService
Next

Set Service = Nothing
Set ServiceSet = Nothing