Two PowerShell scripts for retrieving user info from Active Directory

Obtaining user object information via Active Directory Users And Computers is fine for the one-time use, but it falls short for batch tasks. These two scripts make it easy to pull user information via PowerShell.

One of the enhancements for Windows Server 2008 R2 is the Active Directory Module for PowerShell. This PowerShell environment has a number of commands that are optimized for Active Directory, including features not available through the Active Directory Users And Computers (ADUC) interface, such as the Active Directory Recycle Bin.

The day-to-day administration of user account objects is frequently done in ADUC, but many tasks require administrators to retrieve user information for export. There are plenty of command-line tools for flat dumps, exports, and best practices. (See 10 ways to benchmark your Active Directory environment.) But the new Active Directory Module for PowerShell is the most powerful tool available for the administrator today. Here are a couple of PowerShell scripts to retrieve user information that will help you gain visibility and enforce account policies.

Note: This article is also available as a PDF download.

Script 1: Show user accounts with a non-expiring password

The following PowerShell script will show user accounts with the password set to not expire, sorted by the user name, object class (user, computer, etc.), and UPN fields:

Search-ADAccount -PasswordNeverExpires | FT Name,  ObjectClass, UserPrincipalName
The output will list user accounts that do not have a password expiration, as shown in Figure A.

Figure A

Script 2: Display phone number values for all user accounts

Many organizations use Active Directory as a telephone directory. But there are usually some phone numbers that are unaccounted for. The following script will show the phone number value for the usernames of all user accounts:

Get-AdUser -Filter * -Properties OfficePhone | FT OfficePhone,UserPrincipalName
Each user and office phone number is displayed with this command, as shown in Figure B.

Figure B

More resources

The Active Directory Module for PowerShell provides an incredible realm for managing all aspects of Active Directory. The following resources can help you springboard additional Active Directory user management with PowerShell: