views:

781

answers:

2

I'm trying to perform some basic AD User managment tasks in C# using .Net 3.5

I've got a System.DirectoryServices.AccountManagement.UserPrincipal object that contains the user details.

I can call user.ExpirePasswordNow() and the user will be forced to changed their password at next login (and the "Active Directory Users and Computers" GUI has the "User must change password at next logon" box checked.

However, I want to test the state of this property and act on it - I don't want to just always set it true via the ExpirePasswordNow() function. How can I do this?

I've found examples suggesting I access the underlying DirectoryEntry and its pwdLastSet propperty - but this appears as an inpenetrable System.__ComObject type - it's probably a IADsLargeInteger but I cannot cast to that type due to its "protection level".

I'm at a loss - can anyone help?

+1  A: 

I remember this from having to find out when the user last set their password, but I never used it. Hope it helps... and I never tried the UserAccountControl attribute, but it looks not-too-crazy.

Pwd-Last-Set Attribute

If this value is set to 0 and the User-Account-Control attribute does not contain the UF_DONT_EXPIRE_PASSWD flag, then the user must set the password at the next logon.

Check out the User-Account-Control, someone included an example of how to read this flag only (as part of a query). It's probably better to just add the attribute to the 'to-be-returned', if that is possible.


I think this should work in 3.5. They made this waaaaay simpler. I can't get a DirectorySearcher object to return me the UserAccountControl flags, only this. Perhaps thats permissions, dunno...

Imports System.DirectoryServices.AccountManagement

Dim pctx = New PrincipalContext(AccountManagement.ContextType.Domain)
Dim p = UserPrincipal.FindByIdentity(pctx, "andrew")
If p.LastPasswordSet.HasValue = False Then
    If p.PasswordNeverExpires = False Then
        Console.WriteLine("You should have to enter a password next time!")
    End If
End If
Andrew Backer
Thanks. That seems to do the job. I've spent ages trying to get this to work via the PwdLastSet and playing with the UserAccountControl (which seems to not accurately reflect all the flags it contains!!)
Grhm
Glad it worked :) Twas a shot in the dark, since I can't mess with my own account. Also, when using a DirectorySearcher the __comObject stuff (at least the base types) are converted to .net types for you, like pwdLastSet.
Andrew Backer
A: 

This might help:

Password expiration email utility

I had trouble finding a free utility that would send employees emails before their windows passwords were ready to expire, so I wrote a C# console application that does it.

Philip Wallace