13

我在一个旧线程上找到了这段代码来关闭本地机器:

using System.Management;

void Shutdown()
{
    ManagementBaseObject mboShutdown = null;
    ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
    mcWin32.Get();

    // You can't shutdown without security privileges
    mcWin32.Scope.Options.EnablePrivileges = true;
    ManagementBaseObject mboShutdownParams =
             mcWin32.GetMethodParameters("Win32Shutdown");

    // Flag 1 means we want to shut down the system. Use "2" to reboot.
    mboShutdownParams["Flags"] = "1";
    mboShutdownParams["Reserved"] = "0";
    foreach (ManagementObject manObj in mcWin32.GetInstances())
    {
        mboShutdown = manObj.InvokeMethod("Win32Shutdown", 
                                       mboShutdownParams, null);
    }
}

是否可以使用类似的 WMI 方法重新启动标记“2”的远程机器,我只有机器名称,而不是 IP 地址。

编辑:我目前有:

SearchResultCollection allMachinesCollected = machineSearch.FindAll();
Methods myMethods = new Methods();
string pcName;
ArrayList allComputers = new ArrayList();
foreach (SearchResult oneMachine in allMachinesCollected)
{
    //pcName = oneMachine.Properties.PropertyNames.ToString();
    pcName = oneMachine.Properties["name"][0].ToString();
    allComputers.Add(pcName);
    MessageBox.Show(pcName + "has been sent the restart command.");
    Process.Start("shutdown.exe", "-r -f -t 0 -m \\" + pcName);
}

但这不起作用,我更希望 WMI 继续前进。

4

4 回答 4

15

要将 WMI 查询发送到远程计算机,您只需在对象中指定该计算机的名称(或 IP 地址)ManagementScope

我对 C# 不太熟悉,但这是我使用 MSDN 和WMI Code Creator提出的一个示例(顺便说一下,这是一个用于生成 WMI 代码的出色工具,并且支持 C# 等)。希望这段代码能给你这个想法。

免责声明:此代码未经测试。)

using System;
using System.Management;
...

void Shutdown()
{
    try
    {
        const string computerName = "COMPUTER"; // computer name or IP address

        ConnectionOptions options = new ConnectionOptions();
        options.EnablePrivileges = true;
        // To connect to the remote computer using a different account, specify these values:
        // options.Username = "USERNAME";
        // options.Password = "PASSWORD";
        // options.Authority = "ntlmdomain:DOMAIN";

        ManagementScope scope = new ManagementScope(
          "\\\\" + computerName +  "\\root\\CIMV2", options);
        scope.Connect();

        SelectQuery query = new SelectQuery("Win32_OperatingSystem");
        ManagementObjectSearcher searcher = 
            new ManagementObjectSearcher(scope, query);

        foreach (ManagementObject os in searcher.Get())
        {
            // Obtain in-parameters for the method
            ManagementBaseObject inParams = 
                os.GetMethodParameters("Win32Shutdown");

            // Add the input parameters.
            inParams["Flags"] =  2;

            // Execute the method and obtain the return values.
            ManagementBaseObject outParams = 
                os.InvokeMethod("Win32Shutdown", inParams, null);
        }
    }
    catch(ManagementException err)
    {
        MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
    }
    catch(System.UnauthorizedAccessException unauthorizedErr)
    {
        MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
    }
}
于 2010-05-27T20:11:02.330 回答
4

我也遇到了麻烦。WMI 可能会误导类和对象的方法。我的解决方案是使用 C# 和 WMI 重新启动网络上的主机,但对于本地机器很容易简化:

private void rebootHost(string hostName)
{
    string adsiPath = string.Format(@"\\{0}\root\cimv2", hostName);
    ManagementScope scope = new ManagementScope(adsiPath);
    // I've seen this, but I found not necessary:
    // scope.Options.EnablePrivileges = true;
    ManagementPath osPath = new ManagementPath("Win32_OperatingSystem");
    ManagementClass os = new ManagementClass(scope, osPath, null);

    ManagementObjectCollection instances;
    try
    {
        instances = os.GetInstances();
    }
    catch (UnauthorizedAccessException exception)
    {
        throw new MyException("Not permitted to reboot the host: " + hostName, exception);
    }
    catch (COMException exception)
    {
        if (exception.ErrorCode == -2147023174)
        {
            throw new MyException("Could not reach the target host: " + hostName, exception);
        }
        throw; // Unhandled
    }
    foreach (ManagementObject instance in instances)
    {
        object result = instance.InvokeMethod("Reboot", new object[] { });
        uint returnValue = (uint)result;

        if (returnValue != 0)
        {
            throw new MyException("Failed to reboot host: " + hostName);
        }
    }
}
于 2012-01-18T06:01:53.530 回答
2

如果您需要非 WMI 解决方案,可以使用 shutdown 命令。

shutdown [{-l|-s|-r|-a}] [-f] [-m  [\\ComputerName]] [-t xx] [-c "message"] [-d[u][p]:xx:yy] 

使用 -m 关闭远程机器。

有关更多信息,请参阅此链接。 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/shutdown.mspx

于 2010-05-29T11:04:41.070 回答
0

这会像沙姆一样工作

gwmi win32_operatingsystem -ComputerName xxxxxxxxxxxx | Invoke-WmiMethod -Name reboot
于 2014-06-27T16:15:42.437 回答