When accounts are disabled, sometimes people often need to audit these accounts and gather specific information from Active Directory. This blog post will walk through a practical PowerShell script to extract description attributes and last login timestamps for a list of disabled user accounts.
What was the issue?
Recently, I faced a common scenario in IT administration: I received a text file containing hundreds of User Principal Names (UPNs) for disabled accounts in our organization.
I was then asked for a report including each account's description and last login timestamp from Active Directory. Doing this manually would be tedious and error-prone.
The Solution: PowerShell + Active Directory Module
PowerShell, coupled with the Active Directory module, provides powerful capabilities for querying and managing AD objects.
- Reads a list of UPNs from a text file
- Queries Active Directory for each user
- Extracts the description attribute and last login timestamp
- Exports the results to a CSV file for easy analysis
Script Breakdown
Let's examine the key components of this script and understand how they work:
Importing the Active Directory Module
Import-Module ActiveDirectory
This line loads the Active Directory module, which provides cmdlets for interacting with AD objects. This module must be installed on your system, which is typically available through Remote Server Administration Tools (RSAT) on a domain-joined machine.
File Input and Output Setup
$filePath = "C:\Scripts\mbx_disabledaccounts.txt"
$upns = Get-Content $filePath
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$outputFile = "C:\Scripts\AD_UserInfo_$timestamp.csv"
Above I have specify the path to our input file containing the list of UPNs and read its contents. I also create a timestamped filename for our output CSV, which helps with version tracking when the script is run multiple times.
Progress Tracking
$total = $upns.Count
$current = 0
$startTime = Get-Date
foreach ($upn in $upns) {
$current++
$percentComplete = [math]::Round(($current / $total) * 100, 2)
# ...progress calculation code...
Write-Progress -Activity "Processing AD Account Information" -Status "$current of $total
($percentComplete%)" -PercentComplete $percentComplete
-SecondsRemaining $estimatedTimeRemaining
This section adds a professional touch to the script by showing a progress bar with time estimates. When processing hundreds or thousands of accounts, this feedback is invaluable to the operator.
Querying Active Directory
$user = Get-ADUser -Filter "UserPrincipalName -eq '$upn'"
-Properties Description, LastLogonTimestamp, Enabled, whenCreated
This is where the magic happens. For each UPN, the script queries Active Directory using the Get-ADUser
cmdlet. The -Filter
parameter finds the exact user, and the -Properties
parameter specifies which attributes to retrieve beyond the default ones.
Handling LastLogonTimestamp
if ($user.LastLogonTimestamp) {
$lastLogon = [DateTime]::FromFileTime($user.LastLogonTimestamp)
} else {
$lastLogon = "Never logged in"
}
The LastLogonTimestamp
in AD is stored in a special format called "Windows FileTime." This code converts it to a readable datetime format using the FromFileTime
method. If no timestamp exists the script notes that the user has never logged in.
Creating Custom Objects
$userInfo = [PSCustomObject]@{
UPN = $upn
DisplayName = $user.Name
Description = $user.Description
Enabled = $user.Enabled
CreatedDate = $user.whenCreated
LastLogonTimestamp = $lastLogon
}
For each user, the script creates a custom PowerShell object with properties for all the information listed. This structured approach makes the data easy to work with and export.
Error Handling
try {
# Query AD logic
} catch {
Write-Host "Could not find user $upn in AD: $_" -ForegroundColor Yellow
# Create object for users not found
}
The script uses try/catch blocks to gracefully handle errors, such as when a UPN in the list doesn't exist in Active Directory. This ensures the script continues running even if some accounts can't be found.
Exporting to CSV
$results | Export-Csv -Path $outputFile -NoTypeInformation
Finally, the script export all the collected data to a CSV file, which can be opened in Excel or other tools for further analysis and reporting.
Executing the Script
To use this script in your environment:
- Ensure you have the Active Directory module installed
- Save the script to a .ps1 file (e.g.,
Get-DisabledADUserInfo.ps1
) - Update the
$filePath
variable to point to your list of UPNs - Run the script in PowerShell with administrative privileges
.\Get-DisabledADUserInfo.ps1
🔐 Security Considerations
When running this script, be aware of these security aspects:
- The script requires appropriate AD read permissions
- Consider who has access to the output CSV, as it contains user information
- Secure the PowerShell script file itself to prevent unauthorized modifications.
Scripts
The script is not available on this blog because it’s quite lengthy so if you would like it, please email me at