PowerShell Script - Active Directory Password Expiration Report
It's not always easy to monitor changes to Active Directory and generate useful reports. Powershell can be a great help. Unlike Vbscript, Powershell was designed specifically with network and system administrators in mind. Because of this focus administrators can accomplish tasks in Powershell with a fraction of the code it takes to perform the same tasks with vbscript. For example, remember the procedure for writing to a .csv file?
objfile.writeline variable1 & "," & variable2 & "," variable3 & "," variable4
Blah blah blah. All of those commas (",") just to get a properly formatted .csv file. Then we still have to go back and add the column headings. What a pain. Now let's do the same thing in Powershell.
Export-Csv -Path
Powershell includes a cmdlet specifically for handling .csv files. Combining this built in cmdlet with the QADUser cmdlet from Quest Software we can create a simple Active Directory password expiration report. Here's the code:
The first line is the path to your .csv file. It can be a local or network location.
$strPath = "c:\scripts\myreport.csv"
Use the next 4 lines to get the current domain and filter on the User object.
$dom=[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(objectClass=User)"
The next line uses QADUser cmdlet to get all users except those with the Password Never Expires flag set.
Get-QADUser -IncludeAllProperties | where {($_.PasswordNeverExpires -eq $False)} |
Use the next line to choose which AD attributes to include in the report. Each attribute will create a column heading with the same name.
Select-Object sn, givenanme, SamAccountName, passwordexpires |
Finally, export the data.
Export-Csv -Path $strPath
That's it! A simple Powershell script Active Directory password expiration report. Now compare this code to this and this. See my point? As with all technology there are several ways to skin a cat. If you have some code that works better than what we've provided please share it with us in the comments so we can all benefit from your knowledge!