SoFunction
Updated on 2025-03-07

C# implements the method of remotely shutting down or restarting the computer

This article describes how C# implements remote shutdown or restarting the computer. Share it for your reference. The details are as follows:

/// <summary>
/// Remotely shut down or restart the computer/// </summary>
/// <param name="str">Command</param>/// <param name="ip">ip address</param>static void Invoke(string str, string ip)
{
 //Define some options for connecting to remote computers ConnectionOptions options = new ConnectionOptions();
  = "administrator";
  = "Btmu@123";
 ManagementScope scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", options);
 try
 {
  //Connect the remote computer with the given administrator username and password  ();
  ObjectQuery oq = new ObjectQuery("select * from win32_OperatingSystem");
  ManagementObjectSearcher query1 = new ManagementObjectSearcher(scope, oq);
  ManagementObjectCollection queryCollection1 = ();
  foreach (ManagementObject mo in queryCollection1)
  {
   string[] ss = { "" };
   if (str == "Restart")
   {
    ("Reboot", ss);
   }
   if (str == "Shut down the computer")
   {
    ("Shutdown", ss);
   }
  }
 }
 catch (Exception er)
 {
  ("connect" + ip + "An error occurred, the error message is:" + );
 }
}

I hope this article will be helpful to everyone's C# programming.