| |

Management task: Remote shutdown utility

I run a simple web server to serve as a storage medium for my mobile devices (I don’t like using dropbox or other online storage solutions because they don’t offer much space and they hogs up bandwidth unnecessarily). Before I go to sleep I usually shut down the server to save energy, but in order to do so, I have to have another computer turned on to perform remote access into the server and shut it down via command line. Occasionally, I would turn off my work computer before I remember that I want to shut down the server and I’m too lazy by then to turn on my work computer again.

That’s why I wanted an application that is capable of shutting down Windows on my behalf. The scenario is like this: because I can access FTP service from my phone, I will create a file, namely ‘shutdown’; when the server sees this file, it will delete the file and initiate shutdown. Quite simple.

To shut down, I use Windows management interface (System.Management namespace in C#)

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

From here

And the rest is just a loop to check if the file exists

        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            while (true)
            {
                if (!System.IO.File.Exists("D:\Shutdown"))
                {
                    Thread.Sleep(500);
                }
                else
                {
                    System.IO.File.Delete("D:\Shutdown");
                    Shutdown();
                    return;
                }
            }
        }

That’s it, I run the application and it will wait until I create a file named ‘shutdown’ in D:, it will perform shutdown and quit

Here’s the sample code and binary

Leave a Reply

Your email address will not be published. Required fields are marked *