How to check if Active Directory user password is expired on specified days (PowerShell)

Introduction

This PowerShell Script shows how to use Windows PowerShell to check if user account password is expired.

Scenarios

In many cases, IT admins always encounter a fair number of tickets were related to problems with a user’s password. Often it had expired and they were having issues resetting it and needed to logon immediately. This script can scan all users account and check if user account password is expired.

Script

Step1: Run the script in the Windows PowerShell Console, type the one command: Import-Module <Script Path> at the prompt.

For example, type Import-Module C:\Script\GetADUserPasswordExpiration.psm1

This is shown in the following figure.

Step 2: You can type the command Get-Help Get-OSCLastLogonTime –Full to display the entire help file for this function, such as the syntax, parameters, or examples.

Example

Example 1: Type Get-OSCADUserPasswordExpiration -SamAccountName "doris","katrina" -NextDay 10 command in the Windows PowerShell Console.

This command will check if account password has expired within next 10 days.
 

Example 2: Type Get-OSCADUserPasswordExpiration –CsvFilePath C:\Script\SamAccountName.csv -NextDay 10 command in the Windows PowerShell Console.

This command will check if a batch of accounts password have expired within next 10 days.

Note: the CSV File format must follow the format below:

Here are some code snippets for your reference.

PowerShell
Edit|Remove
Function ADPasswordExpiration([String]$SamAccountName,[Int]$NextDay) 
{ 
    $MaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.TotalDays 
    $PasswordBeginDate = (Get-Date).AddDays(-$MaxPasswordAge) 
    $PasswordExpriyDate = (Get-date).AddDays(-($MaxPasswordAge-$NextDay)) 
  
    $ADPasswordInfo = Get-ADUser -Filter {Enabled -eq $true -and SamAccountName -eq $SamAccountName}` 
     -Properties PasswordNeverExpires,PasswordLastSet,PasswordExpired ` 
    | Select-Object SamAccountName,@{Expression={$($_.PasswordNeverExpires -eq $false) ` 
     -and $($_.PasswordLastSet -ge $PasswordBeginDate.Date) -and ` 
     $($_.PasswordLastSet -le $PasswordExpriyDate.Date)};Label="ExpiredOnNext($NextDay)Day"},` 
     PasswordLastSet,PasswordExpired 
     
    $ADPasswordInfo 
  
}

Prerequisite

Windows PowerShell 2.0