How to create powershell list accounts last password set 4 months and add them to an AD Group

ManUnderContruction 21 Reputation points
2022-12-05T10:03:44.193+00:00

Hi Experts,

I am not an expert in pwoershell, and just only beginner. We have a requirement to add users to AD group named "BannedUsers" if their last password change is more than 4 months. Is this possible?

Thank you!

Windows for business Windows Client for IT Pros Directory services Active Directory
Windows for business Windows Server User experience PowerShell
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2022-12-05T20:35:32.493+00:00

    This might be what you're looking to do:

    $BanMeDate = (Get-Date).Date.AddMonths(-4)  
      
    Get-ADUser -Filter * -Properties PwdLastSet  |  
        ForEach-Object{  
            if ([DateTime]::FromFileTime($_.PwdLastSet) -le $BanMeDate){  
                Add-ADGroupMember -Identity BannedUsers -Members $_.SamAccountName -WHATIF  
            }  
        }  
    

    Be sure you TEST THIS! When you're satisfied that it isn't going to destroy your organization, remove the "-WHATIF" parameter.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. ManUnderContruction 21 Reputation points
    2022-12-06T01:40:58.173+00:00

    Thanks @Rich Matheisen , I tried it out but it seems there's issue with the integer conversion, getting the error as per below:

    Could not compare "133146771438393590" to "08/06/2022 00:00:00". Error: "Cannot convert value "8/6/2022 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""
    At line:5 char:14

    • if ($_.PwdLastSet -le $BanMeDate){
    • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : ComparisonFailure

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.