Shutting down a PC using WMI and C#

I found myself needing to re-work some code that was originally part of my WMI presentation from 2003.

After a little bit of re-writing and a little bit of searching, I re-wrote my original Delphi routine, which looked like this:

[code lang=”Pascal”]
procedure TfrmMain.btnShutdownClick(Sender: TObject);
wmiLocator: TSWbemLocator;
wmiServices: ISWbemServices;
wmiObjectSet: ISWbemObjectSet;
wmiObject: ISWbemObject;
Enum: IEnumVariant;
ovVar: OleVariant;
lwValue: LongWord;

wmiLocator := TSWbemLocator.Create(self);
wmiServices := wmiLocator.ConnectServer( edtComputer.Text, ‘root\cimv2’, edtUser.Text, edtPass.Text, ”, ”, 0, nil);

wmiServices.Security_.Privileges.Add(wbemPrivilegeShutdown, True);
wmiObjectSet := wmiServices.ExecQuery(‘SELECT * FROM Win32_OperatingSystem WHERE Primary=True’, ‘WQL’, wbemFlagReturnImmediately, nil);
Enum := (wmiObjectSet._NewEnum) as IEnumVariant;
while (Enum.Next(1, ovVar, lwValue) = S_OK) do begin
wmiObject := IUnknown(ovVar) as SWBemObject;
wmiObject.ExecMethod_(‘Shutdown’, nil, 0, nil);


…it now looks like this:

[code lang=”C’#”]
using System.Management;

public enum ShutDown
LogOff = 0,
Shutdown = 1,
Reboot = 2,
ForcedLogOff = 4,
ForcedShutdown = 5,
ForcedReboot = 6,
PowerOff = 8,
ForcedPowerOff = 12

ManagementClass W32_OS = new ManagementClass(“Win32_OperatingSystem”);
ManagementBaseObject inParams, outParams;
int result;

W32_OS.Scope.Options.EnablePrivileges = true;
foreach(ManagementObject obj in W32_OS.GetInstances())
inParams = obj.GetMethodParameters(“Win32Shutdown”);
inParams[“Flags”] = ForcedShutdown;
inParams[“Reserved”] = 0;

outParams = obj.InvokeMethod(“Win32Shutdown”, inParams, null);
result = Convert.ToInt32(outParams[“returnValue”]);
if (result !=0) throw new Win32Exception(result);

Here’s a link to more information about this on the MSDN.

[job for tonight – sort out this code format…once and for all]

3 thoughts on “Shutting down a PC using WMI and C#”

  1. Hi,

    I have done something very similar stuff but I do not know how to add comments while shutting down win 2003

    ShutDownTracker is meant for viata and longhorn …..

Comments are closed.