Today, I am miserable. I accidentally deleted thousands of users on the customer's Active Directory. I have been puzzled after I found that the deleted user was accidentally deleted, because according to the log recorded by the program, all operations performed on users with accidental deletion are newly added. The result of the newly added operation is the "PrincipalExistsException, the object already exists" exception. After the addition fails, no code for the AD operation is executed. After carefully checking the program, it is impossible to perform the delete operation. The strange thing is that the account disappears every time the UserPrincipal. Save () method is executed !!?
Next, a small program is carefully tested, and the code used for testing is first pasted:
Static void Main (string [] args) {string container = "DC = contosocorp, DC = local"; using (PrincipalContext context = new PrincipalContext (ContextType. domain, "contosocorp. local ", container, ContextOptions. negotiate, "administrator", "p @ ssw0rd") {string emailPrefix = "zhanqing"; string password = "p @ ssw0rd"; string name = "Zhan Qing "; string id = "56447"; UserPrincipal userPri = new UserPrincipal (context, emailPrefix, password, true); userPri. description = id; userPri. displayName = name + id; userPri. name = name + id; userPri. samAccountName = emailPrefix; userPri. userPrincipalName = emailPrefix + "@" + "contosocorp. local "; try {userPri. save ();} catch (Exception ex) {Console. writeLine (ex. message) ;}} Console. read ();}
I used several existing accounts in the Active AD to test the function. The account disappears after the account is saved. After careful analysis, I found that the only difference with the formal program is: in the test code, the container associated with the context is always the container of the Active Directory, and the container associated with the context in the official release program is the container of the OU where the account is located. Change the value of the container and try again, consistent with the OU where the account "zhanqing" is located:
String container = "DC = Information Technology headquarters, DC = contosocorp, DC = local ";
I was surprised when the execution of Console. WriteLine (ex. Message) was completed, the account "zhangqing" in AD was deleted!
This is something I cannot understand.
Then I made some attempts and found that when userPri. after Name = name + id is commented out, even if the container associated with the context is the same as that of the OU where the account in the AD is located, the account will not be deleted when the Save method is called, but as long as userPri. the value of Name is the same as the Name of the account in AD and the container of the OU is the same. The account disappears after the Save method is called.
Ah ......