Introduction
I have some Windows services that run under my domain account credentials. When my password expires and I change it, my services generate a log-on failure due to old password. Now I have to change the password for each and every service running under my account. Worse, I have to type the password twice for each service. I just thought there could be a better way to do this and thought of writing this small utility. This utility sets the password for all the services running under my account and I manage to save some keyboard key hits! This utility uses WMI features using C# and .NET. .NET really makes manipulating Windows objects simple and this tip will demonstrate how to do that for this problem.
Above is the UI for this utility where the user needs to provide a new password due to changed log-on details.
Using the Code
Below is a brief description of the code as to how it works:
using System.Management;
using System.Security.Principal;
string queryStr = "select * from Win32_Service where StartName like '";
queryStr += uName.Replace('\\', '%');
queryStr += "'";
ObjectQuery oQuery = new ObjectQuery(queryStr);
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
Once we are done with collecting all the services, we can iterate over them to change the password as shown below:
foreach (ManagementObject oReturn in oReturnCollection)
{
string serviceName = oReturn.GetPropertyValue("Name") as string;
string fullServiceName = "Win32_Service.Name='";
fullServiceName += serviceName;
fullServiceName += "'";
ManagementObject mo = new ManagementObject (fullServiceName);
mo.InvokeMethod("Change", new object[]
{ null, null, null, null, null, null, uName, passWord, null, null, null });
mo.InvokeMethod("StartService", new object[] { null });
}
Points of Interest
It was interesting to know how .NET makes WMI so simple to use. Also, this utility is more helpful if there are more services that are needed by the user and the frequency of password change is high. Otherwise, this could be used as a tutorial on how to do this kind of stuff.
History
- 17th February, 2009: First version of the tip