I'm trying to write some code to create a user in active directory and expire the default password so that they have to change their password the first time they log in. I tried nearly everything. I read a bunch a resources to try figure out why it wouldn't work. However, it still wouldn't work. Then for some I don't remember I decided to close the DirectoryEntry and create a second DirectoryEntry object and use it to expire the password. For some reason that worked. Does someone know why I had to create a second DirectoryEntry object to do this?
Code:Public Sub CreateADUser2(ByVal login As String, ByVal password As String, ByVal displayName As String)
Dim newUserPath As String = ""
Using de As New DirectoryEntry("LDAP://" + UserOU + "," + AdDomain)
' Create user account
Dim users As DirectoryEntries = de.Children
Using newuser As DirectoryEntry = users.Add("cn=" + login, "user")
newUserPath = newuser.Path
' Set properties
SetProperty(newuser, "displayName", displayName)
SetProperty(newuser, "description", Description)
SetProperty(newuser, "userPrincipalName", login + "@" + Domain)
SetProperty(newuser, "scriptPath", LoginScript)
SetProperty(newuser, "SAMAccountName", login)
newuser.CommitChanges()
' Expire password so that they have to change it the next time they login
'' this doesn't do anything here
If de.Properties.Contains("pwdLastSet") Then
de.Properties("pwdLastSet")(0) = 0
Else
de.Properties("pwdLastSet").Add(0)
End If
newuser.CommitChanges()
' Enable account
Dim val As Integer = CInt(de.Properties("userAccountControl").Value)
de.Properties("userAccountControl").Value = val And (Not 2)
newuser.CommitChanges()
' Set password
newuser.Invoke("SetPassword", password)
newuser.CommitChanges()
newuser.Close()
de.Close()
End Using
End Using
Using de As New DirectoryEntry(newUserPath)
' Expire password so that they have to change it the next time they login
'' here it does work
If de.Properties.Contains("pwdLastSet") Then
de.Properties("pwdLastSet")(0) = 0
Else
de.Properties("pwdLastSet").Add(0)
End If
de.CommitChanges()
de.Close()
End Using
End Sub
Thanks,
Scott
