Find Active Directory Users with Expired Password (PowerShell). Are you responsible for managing passwords in your Active Directory (AD) environment? One crucial task is to identify users whose passwords have expired, as these users will no longer be able to log into their accounts until they reset their passwords. This article shows you how to efficiently use PowerShell to find Active Directory users with expired passwords.
Shall we start our article blog about Find Active Directory Users with Expired Password (PowerShell).
Find AD Users with Expired Passwords Using PowerShell
Following this article saves time and effort, as we quickly target specific users for password reset or expiration notifications. Whether you are a network administrator or simply looking to improve the security of your Active Directory environment, this guide provides the information you need to get started.
Prerequisites
If we plan to follow this article, we will need the following:
- A Windows computer joined to an Active Directory domain.
- Installed ActiveDirectory module on the computer.
- The computer must also have at least Windows PowerShell 5.1 or higher.
Finding Users in Active Directory
Before resetting a user password, we must first locate the account. As a result, our first step should be to determine whether or not a reserve exists. To do so, run the Get-ADUser cmdlet with the Identity parameter set to the account’s name.
The Identity parameter accepts one of four identifiers: distinguished name (DN), GUID (objectGUID), Security ID (objectSID), or SAM account name (SAMAccountName).
For example, if we request to reset the password for a specific user, we should first verify that the user exists before issuing an account reset. To do so, copy the following command and paste it into our PowerShell console. Make sure to first change the user name to the correct one:
Get-ADUser -Identity
The command returned the user properties, as shown in the screenshot below, confirming that the account exists and the username is correct:
Finding Users with Expired Password in AD
We can quickly get the password expiration date for a single user by appending and using the attribute msDS-UserPasswordExpiryTimeComputed with the Get-ADUser command:
Get-ADUser -Identity USERNAME -Properties 'msDS-UserPasswordExpiryTimeComputed'
But this line of code will result in a human unreadable output, so we need to add the following line to convert the results into a readable format. To add the line below, we will use the Select-Object -Property command on a new PowerShell pipeline:
Select-Object -Property {[datetime]::FromFileTime($_.”msDS-UserPasswordExpiryTimeComputed”)}
Running the same attribute, msDS-UserPasswordExpiryTimeComputed, with the right filter, we get a list of Active Directory accounts and their password expiration times:
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
We improve the above script by exporting the list of users into a text file we could use later. To do this, we can use the Out-File command that will send the output to a text file:
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object -Property "GivenName" |
Out-File -FilePath .\userslist.txt
The script above generates a file called userslist.txt that we can use later. We have also omitted the ExpiryDate property from the output as we only need the user IDs of accounts that are expired. We use this list for mass remediation, which is discussed later in the article.
Resetting the Active Directory User Password
Now that we have learned how to use Get-ADUser to verify a user account, we know that the result is valid and that the user ID exists. We must now use the Set-ADAccountPassword cmdlet to reset the user’s password.
The Set-ADAccountPassword command changes a user’s password if we supply the old password. If we don’t have the old password, the cmdlet resets it with the Reset parameter.
The new randomly generated password is a 14-character random password with five non AlphaNumeric characters. To execute, open a PowerShell window, copy the code, paste it into PowerShell, and press Enter:
$username = USERNAME
Add-Type -AssemblyName 'System.Web'
$randomPassword = [System.Web.Security.Membership]::GeneratePassword(14, 5)
$newPassword = $randomPassword | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $username -NewPassword $newPassword -Reset |
Set-ADUser -ChangePasswordAtLogon true
$randomPassword
- Line 1: Specifies the username whose password to reset. Make sure to replace the USERNAME string with the actual user ID.
- Line 2: Imports the System.Web .NET assembly object class.
- Line 3: Generates a random password that is 14 characters long with five non alphanumeric characters.
- Line 4: Converts the plain text password to a secure string password object.
- Line 5: Facilitates the reset of the password.
- Line 6: Enforces the AD account to change the password upon next logon.
- Line 7: Displays the new password in the console. However, we are not recommending this for security purposes. Line 6 takes care of the password change to the user’s liking and is considered as the best practice for this procedure.
Improve your Active Directory Security & Azure AD
Try us out for Free, Access to all features. – 200+ AD Report templates Available. Easily customise your own AD reports.
Writing the Active Directory Password Reset Tool
We now have a script that we use to reset a user’s password. The next step is to make our script into a tool. A reusable tool executes the same actions with minimum manual user actions.
When building a tool, one crucial aspect is that whoever runs the tool should not have to edit the code every time. But unfortunately, our code still requires the user to edit the $username variable.
Instead of allowing our tool’s users to change the values manually, why not write a script that accepts parameters? To do so, take the following steps:
- Open Windows PowerShell ISE.
- Create a new PowerShell file and save the file under the name Reset-ADPassword.ps1. Save the script in our preferred location. This article saves the file in the C:\PS\scripts folder.
- Please copy and paste the code below into our script editor before saving the script.
param (
$username
)
if (-not($username)) {
Write-Host "Username not found. Exiting script"
return $null
}
try {
$null = Get-ADUser -Identity $username -ErrorAction Stop
} catch {
Write-Host $_.Exception.Message
return $null
}
$randomPassword = [System.Web.Security.Membership]::GeneratePassword(14, 5)
$newPassword = $randomPassword | ConvertTo-SecureString -AsPlainText -Force
try {
Set-ADAccountPassword -Identity $username -NewPassword $newPassword -Reset -ErrorAction Stop
Set-ADuser -Identity $username -ChangePasswordAtLogon $true
[pscustomobject]@{
Username = $username
NewPassword = $randomPassword
}
} catch {
Write-Host "There was an error performing the password reset. Please find additional information below."
Write-host $_.Exception.Message
return $null
}
- Line 1: Adds a parameter called username.
- Line 5: Checks if the user provided a username value. The if block also shows a message and exits the script if the condition is met.
- Line 10: Checks if the username is valid or not.
- Line 12: Validates if the username is invalid. Displays a message and stops the script execution.
- Line 17: Generates a random password that is 14 characters long with five non-alphanumeric characters.
- Line 18: Converts the plain text password to a secure string password object.
- Line 20: Facilitates the reset of the password.
- Line 22: Enforces the AD account to change the password upon next logon.
- Line 24: Displays the new password in the console. However, we are not recommending this for security purposes. Line 6 will take care of the password change to the user’s liking and is considered the best practice for this procedure.
- Line 28: Displays an error message if the reset has failed.
Example Executions of the AD Password Reset Tool
A PowerShell console pane is already available if we use Windows PowerShell ISE. If not, we should launch a separate PowerShell session. Change the current working directory to the destination folder where the script was saved, such as Set-Location C:\PS\Scripts.
Resetting the Password of a Single User
Suppose we need to reset one user’s password. First, run the Active Directory password reset tool and specify which username to target. For example, to reset a single user’s password, run the script as shown below:
.\Reset-ADPassword.ps1 -username USERNAME
As a result, the script resets the password and displays it on the screen. For example, this output sends the new password to the affected user:
Resetting the Password of Multiple Users
Fortunately, we can loop through a list in PowerShell using arrays and the foreach loop. In addition, the ForEach-Object cmdlet in PowerShell allows us to process multiple items simultaneously. This cmdlet lets us pass various items through the pipeline.
To reset the passwords of multiple users, create an array with two or more usernames. The array items are then passed through the pipeline, where the ForEach-Object PowerShell command runs the password reset tool on each username.
@('user1', 'user2') | ForEach-Object {.\Reset-ADPassword.ps1 -username $PSItem}
However, we improve this if we remediate more than two user accounts. Remember the text file that we generated earlier? We make use of it in this section.
We must read the text file containing the user accounts and run the AD password reset tool on each one. To do so, use the Get-Content cmdlet to import the content of the text file into PowerShell. After that, the script sends the data to the pipeline and runs the AD password reset script on each account.
Get-Content .\userslist.txt | ForEach-Object {.\Reset-ADPassword.ps1 -username $PSItem}
After execution the snippet above, we will have reset multiple user passwords in a single runtime.
Thank you for reading article blog Find Active Directory Users with Expired Password ( PowerShell). We will conclude it now.
Find AD Users with Expired Passwords PowerShell Conclusion
In conclusion, finding Active Directory users with expired passwords using PowerShell is a straightforward process that saves us time and effort. Using the Get-ADUser cmdlet and filtering for users with expired passwords, you can quickly identify and target specific users for password reset or expiration notifications. This command is handy for organizations with large numbers of users, as it allows you to proactively manage password expiration and reduce the risk of security breaches.
Try InfraSOS for FREE
Invite your team and explore InfraSOS features for free
- Free 15-Days Trial
- Easy Setup
- Full Access to Enterprise Plan
Related posts:
- Get-ADUser Filter OU – List Users from a Specific OU
- Top 5 Active Directory Powershell Scripts for Active Directory (Users / Groups)
- Office 365 Identity & Access: Manage Users & Permissions
- SSPR: Enable Azure Active Directory Self-Service Password Reset
- Get-MgUserMemberOf – List Group Memberships of Azure AD User PowerShell