Wednesday, August 22, 2012

Get PassWord Expiration date for a Domain Account with #PowerShell

#PowerShell, I recently I switch to it because of work and man, it is indeed a powerfull #scripting language.  This little script basically gets the date of when a password of an #AD (Active Directory) account will expire.

Let me know if you see anything that can be optimized.

I'll post some more little #powershell #scripts that I've been using to make things a bit easier on the admin side.

# luis@yaxmail.com - 20120822
# This cripts takes the passed valued and verifies against the AD to confirm it is a SamAccountName
# If determines it is a SamAccountName, it checks what the value is for PasswordNeverExpires atribute 
# If PasswordNeverExpires is False for SamAccountName, it checks when the password will expire

# Get-MyModule function came from the scripting guy
# http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/11/hey-scripting-guy-weekend-scripter-checking-for-module-dependencies-in-windows-powershell.aspx
#####
$AD = "ActiveDirectory"
Function Get-MyModule { 
    Param([string]$name) 
        if(-not(Get-Module -name $name)) { 
            if(Get-Module -ListAvailable | Where-Object { $_.name -eq $name }) { 
            Import-Module -Name $name 
            } else { 
            $false 
            }
        }  
} 
Get-MyModule -name $AD
#####

$ValueGiven = $args[0]
$User2Check = $ValueGiven.ToUpper()
$VerifyUser = (Get-ADUser -LDAPFilter "(SamAccountName=$User2Check)").SamAccountName
$VerifyExpiration = (Get-ADUser -LDAPFilter "(SamAccountName=$User2Check)" -Properties *).PasswordNeverExpires
$separator = "---------------------------------------------------------"

if ($VerifyUser) {
    
    # This comparison had to use the "like" operator since $VerifyExpiration has additional invisible characters
    # If you know how to isolate value, I would love to know
    if ($VerifyExpiration -like '*False*') {

    $separator
    $WillExpire = [datetime]::FromFileTime((Get-ADUser -Identity $User2Check -Properties "msDS-UserPasswordExpiryTimeComputed")."msDS-UserPasswordExpiryTimeComputed")
    write-host "Password for"$User2Check" expires on: "$WillExpire    
    $separator
    
    } elseif ($VerifyExpiration -like '*True*') {

    $separator
    write-host "Password does not expire for user: "$User2Check
    $separator
    
    }

} else {

$separator
write-host "User provided:"$User2Check", is not in the Active Directory"
$separator

}