WMI to reboot remote machine

前端 未结 4 1236
长发绾君心
长发绾君心 2020-11-30 09:18

I found this code on an old thread to shutdown the local machine:

using System.Management;

void Shutdown()
{
    ManagementBaseObject mboShutdown = null;
           


        
4条回答
  •  旧巷少年郎
    2020-11-30 09:54

    I had trouble with this also. WMI can be misleading with methods for classes and object. My solution is for rebooting a host on the network with C# and WMI, but is easily simplified for local machine:

    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);
            }
        }
    }
    

提交回复
热议问题