Skip to content

Instantly share code, notes, and snippets.

@soulhakr
Last active January 23, 2023 19:06
Show Gist options
  • Save soulhakr/545507a9b16b54c328efc6ccdd4aa8e7 to your computer and use it in GitHub Desktop.
Save soulhakr/545507a9b16b54c328efc6ccdd4aa8e7 to your computer and use it in GitHub Desktop.
[Get Active Directory User Password Expiration] #powershell #windows #activedirectory #usermanagement
# Get the date and time of an Active Directory user account given the username
#
# If the password is going to expire in the next 30 days the script will exit with
# 1, otherwise it will exit with 0.
# If the password is set to never expire, the script will return "Never"
# If the user account is not found, the script will return "Not Found
# Usage: Get-ADUserPasswordExpiration.ps1 -Identity <username>
# Example: Get-ADUserPasswordExpiration.ps1 -Identity jsmith
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string]$UserName
)
$ADUser = (Get-ADUser -Filter { SamAccountName -eq $UserName } -Properties msDS-UserPasswordExpiryTimeComputed, PasswordNeverExpires -ErrorAction SilentlyContinue)
$expiryTimeComputed = ($ADUser | Select-Object -ExpandProperty msds-userpasswordExpiryTimeComputed -ErrorAction SilentlyContinue)
$PasswordNeverExpires = ($ADUser | Select-Object -ExpandProperty PasswordNeverExpires -ErrorAction SilentlyContinue)
if ($null -eq $ADUser) {
Write-Host 'Not Found'
exit 1
}
if ($PasswordNeverExpires -eq $true) {
Write-Host 'Never'
exit 0
} else {
$passwordExpirationDate = [DateTime]::FromFileTime($expiryTimeComputed)
$timeUntilExpiration = $passwordExpirationDate - (Get-Date)
Write-Host $passwordExpirationDate.ToString('MM/dd/yyyy hh:mm:ss tt')
if ($timeUntilExpiration.Days -le 30) {
exit 1
} else {
exit 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment