Active Directory Friday: Find user accounts that have not changed password in 90 days

Today I am starting a new section my blog. Each friday I will post an example of a task I have performed in Active Directory using PowerShell. For this I will usually not use any of the Active Directory Cmdlets, so there is no dependancy on any modules to be present on a system in order to execute these queries. If you have any suggestions for a task or query that could be discussed, please drop me a line in the comments and I will consider it for next week. Today I will start with a query that gathers the samaccountname, pwdlastset and if an account is currently enabled or disabled. Note that the commands in this article only query Active Directory so no changes to objects will be made. First we will create a variable, $PwdDate, that contains the filetime of a date ninety days ago:

1
$PwdDate = (Get-Date).AddDays(-90).ToFileTime()

Then an DirectoryServices.DirectorySearcher object will be created with the LDAP Query to locate only user accounts that have their passwords last set on a date 90 or more days ago:

1
2
3
4
$Searcher = New-Object DirectoryServices.DirectorySearcher -Property @{
    Filter = "(&(objectclass=user)(objectcategory=person)(pwdlastset<=$PwdDate))"
    PageSize = 500
}

ForEach user account found we output its samaccountname, pwdlastset and enabled or disabled state of the account:

1
2
3
4
5
6
7
$Searcher.FindAll() | ForEach-Object {
    New-Object -TypeName PSCustomObject -Property @{
        samaccountname = $_.Properties.samaccountname -join ''
        pwdlastset = [datetime]::FromFileTime([int64]($_.Properties.pwdlastset -join ''))
        enabled = -not [boolean]([int64]($_.properties.useraccountcontrol -join '') -band 2)
    }
}

Note that the -join ” operator this is used to unwrap the properties, which are by default provided as System.DirectoryServices.ResultPropertyValueCollection objects. Alternatively the array indexing notation [0] could be used, this has the downside that when a property is empty it will cause the script to display errors. The full code used in this example is available here in the TechNet Script Repository: http://gallery.technet.microsoft.com/scriptcenter/Query-for-AD-Users-that-b87acf2f

Share

One thought on “Active Directory Friday: Find user accounts that have not changed password in 90 days

  1. Pingback: Find AD users who's password hasn't been changed in x amount of days and who's name doesn't start with yy. - How to Code .NET

Leave a Reply

Your email address will not be published.