Search code examples
powershellazure-active-directory

Powershell script to check Azure AD Users password age


I am trying to simplify my AAD housekeeping tasks by creating a script. However, I am having trouble with...

  1. The "last logon part" in the query does not return value but it works when its by its own
  2. The conversion of last logon from Zulu time to align with other datetime output format
# Work on this after I can get "last logon" value
$timestamp = '2017-08-03T12:30:00.000Z'
$datetime  = ([DateTime]$timestamp).ToUniversalTime()

Can someone provide some guidance on how to do this correctly?

Here is the code:

Get-MsolUser -MaxResults 3 | 
Select-Object DisplayName, 
@{n="UPN";e={$_.UserPrincipalName}},
@{n="Enabled";e={(Get-AzureADUser -ObjectId $_.ObjectId).accountEnabled}},
@{n="PwLastSet";e={($_.LastPasswordChangeTimeStamp)}},
@{n="PwAge";e={(New-TimeSpan -Start ($_.LastPasswordChangeTimestamp) -End (Get-Date) ).Days}},
@{n="Manager";e={(Get-AzureADUserManager -ObjectId $_.ObjectId).UserPrincipalName}},  
@{n="Last Login";e={((Get-AzureADAuditSignInLogs -Filter "UserPrincipalName eq '$($_.UserPrincipalName)'" -Top 1).CreatedDateTime)}}| 
Sort-Object PwAge -descending

Thank you!


Solution

  • Please update the script with correct filter syntax as mentioned below:

    @{n="Last Login";e={(Get-AzureADAuditSignInLogs -Filter "startsWith(userPrincipalName,'$($_.UserPrincipalName)')" -Top 1).CreatedDateTime}

    Sample Output Screenshot

    I used this in a sample script and was able to generate the output as well.