Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

wmi - Change local administrator password in C#

I am looking for a way to change the password of a local user account (local Administrator) on a Windows (XP in this case) machine. I have read the CodeProject article about one way to do this, but this just doesn't seem 'clean'.

I can see that this is possible to do with WMI, so that might be the answer, but I can't figure out how to use the WinNT WMI namespace with ManagementObject. When I try the following code it throws an "Invalid Parameter" exception.

public static void ResetPassword(string computerName, string username, string newPassword){ 
            ManagementObject managementObject = new ManagementObject("WinNT://" + computerName + "/" + username); // Throws Exception
            object[] newpasswordObj = {newPassword};
            managementObject.InvokeMethod("SetPassword", newpasswordObj);
}

Is there a better way to do this? (I'm using .NET 3.5)

Edit: Thanks Ely for pointing me in the right direction. Here is the code I ended up using:

public static void ResetPassword(string computerName, string username, string newPassword) { 
        DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); 
        directoryEntry.Invoke("SetPassword", newPassword);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the DirectoryEntry class instead of ManagementObject class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...