Thursday, February 19, 2015

Getting Active Directory account information using PowerShell

Recently I needed to get Active Directory account expiration dates for a list of users.  To do this, you can always use the venerable "net user" command from the Windows command line.  However, this is painful to run for a large number of users.  Instead, I decided to see if I could use PowerShell and leverage the UserPrincipal class.  Here is the PowerShell script I came up with:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$users = get-content 'users.txt'
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
foreach($username in $users){
 $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
 "------"
 "Name: " + $user."DisplayName"
 "Username: " + $username
 "Account Active: " + $user."Enabled"
 "Account Expiration: " + $user."AccountExpirationDate"
 " "
}

Here is the "users.txt" file....it is just the usernames, one per line:

U1234567
U2345678
U3456789


This gives this output:
------

Name: Smith, Joe
Username: U1234567
Account Active: True
Account Expiration: 01/06/2016 06:00:00

------
Name: Smith, Bob
Username: U2345678
Account Active: True
Account Expiration: 01/06/2016 06:00:00

------
Name: Smith, Billy
Username: U3456789
Account Active: True
Account Expiration: 01/06/2016 06:00:00

Hopefully this gives you some other ideas for how to query Active Directory using PowerShell.