如何使WMI关机/重新启动工作?

时间:2019-04-01 20:30:45

标签: c# .net wpf wmi

所以我一直在为服务器/网络上的Windows 10 PC进行WMI关闭,我尝试了多个代码示例,但通常会出现相同的错误

我已经尝试连接到其他计算机,没有模拟,用户名/密码,并且已经尝试过 我从this来源获得了大部分代码

我希望它可以连接并关闭计算机,但最终出现此错误:

private void systemcontrolsremote(int flag, string target, string username, string password, string domain)
    {
      try
      {
        this.Console.Clear();
        this.Console.Text = "Attpting to execute the command with the additional command line arguments:\nTarget: " + target + "\nUsername: " + username + "\nPassword: " + password + "\nDomain: " + domain + "\n";
        ManagementScope scope = new ManagementScope("\\\\" + target + "\\root\\CIMV2", new ConnectionOptions()
        {
          EnablePrivileges = true,
          Username = username,
          Password = password,
          Authority = "ntlmdomain:" + domain,
          Impersonation = ImpersonationLevel.Impersonate
        });
        try
        {
          scope.Connect();
        }
        catch
        {
          try
          {
            scope.Options.EnablePrivileges = true;
            scope.Connect();
          }
          catch
          {
            try
            {
              scope.Options.Impersonation = ImpersonationLevel.Impersonate;
              scope.Connect();
            }
            catch
            {
              try
              {
                scope.Options.EnablePrivileges = true;
                scope.Options.Impersonation = ImpersonationLevel.Impersonate;
                scope.Connect();
              }
              catch (ManagementException ex)
              {
                this.Console.AppendText("An error occurred while trying to execute the WMI method: " + ex.Message);
              }
              catch (UnauthorizedAccessException ex)
              {
                this.Console.AppendText("Connection error (user name or password might be incorrect): " + ex.Message);
              }
            }
          }
        }
        SelectQuery selectQuery = new SelectQuery("Win32_OperatingSystem");
        foreach (ManagementObject managementObject in new ManagementObjectSearcher(scope, (ObjectQuery) selectQuery).Get())
        {
          ManagementBaseObject methodParameters = managementObject.GetMethodParameters("Win32Shutdown");
          methodParameters["Flags"] = (object) flag;
          managementObject.InvokeMethod("Win32Shutdown", methodParameters, (InvokeMethodOptions) null);
        }
      }
      catch (ManagementException ex)
      {
        this.Console.AppendText("An error occurred while trying to execute the WMI method: " + ex.Message);
      }
      catch (UnauthorizedAccessException ex)
      {
        this.Console.AppendText("Connection error (user name or password might be incorrect): " + ex.Message);
      }
    }```

0 个答案:

没有答案