我正在寻找一种方法来更改Windows(本例中为XP)计算机上的本地用户帐户(本地管理员)的密码。我已阅读 CodeProject文章有关实现此目的的一种方法,但这似乎并不“干净”。

我可以看到这是可能与WMI有关,所以这可能就是答案,但我无法弄清楚如何将WinNT WMI命名空间与ManagementObject一起使用。当我尝试以下代码时,它会抛出“无效参数”。异常。

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

有更好的方法吗? (我正在使用.NET 3.5)

编辑:感谢Ely指出我正确的方向。这是我最终使用的代码:

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);
}
有帮助吗?

解决方案

尝试 DirectoryEntry 类而不是 ManagementObject 类。

其他提示

正如Ely所说,您可以使用System.DirectoryServices代码按照 MSDN 完成此操作:

String myADSPath = "LDAP://onecity/CN=Users,
     DC=onecity,DC=corp,DC=fabrikam,DC=com";

// Create an Instance of DirectoryEntry.
DirectoryEntry myDirectoryEntry = new DirectoryEntry(myADSPath);
myDirectoryEntry.Username = UserName;
myDirectoryEntry.Password = SecurelyStoredPassword;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top