WMI to reboot remote machine

前端 未结 4 1235
长发绾君心
长发绾君心 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:29

    To address WMI queries to a remote computer, you simply specify that computer's name (or IP address) in the ManagementScope object.

    I'm not well up in C#, but here's an example I came up with using MSDN and WMI Code Creator (which is, by the way, an excellent tool for generating WMI code, and supports C# among others). Hope this code will give you the idea.

    (Disclaimer: This code is untested.)

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

提交回复
热议问题