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.

2 comments:

  1. Thanks! This works perfectly.
    How would you go about to export the result to a text file with columns and heads like Username DisplayName etc?

    Br
    Niklas

    ReplyDelete
    Replies
    1. This would be a pretty simple change to the script. Just move the column headings above the loop and print the fields on a single line. Something like this:

      Add-Type -AssemblyName System.DirectoryServices.AccountManagement
      $users = get-content 'users.txt'
      $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain

      "Name,Username,Account Active,Account Expiration"
      foreach($username in $users){
      $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
      $user."DisplayName" + "," +
      $username + "," +
      $user."Enabled" + "," +
      $user."AccountExpirationDate"
      }

      Delete

Note: Only a member of this blog may post a comment.