Powershell script to add user if they are a member of 1 group and if last password change is more than 4 months

ManUnderContruction 21 Reputation points
2022-12-09T08:58:42.533+00:00

Hi experts! :)

I am a noob in powershell, and just starting out exploring it. We have a requirement to add users to AD distribution Group named "Leavers" if their last password change is more than 4 months and they are a member of the AD group "Bannedusers"

Thank you!

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,974 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,628 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Hoekstra Jelle 501 Reputation points
    2022-12-09T10:31:16.007+00:00

    I think this would work, give it a try :)

    $groupname = "Bannedusers"
    $usersingroup = get-group $groupname | get-adgroupmember
    $userlist = foreach ($user in $usersingroup){
    $userproperty = get-aduser $user -properties * | Select-Object Name, PasswordLastSet | Where PasswordLastSet -LT (Get-Date).AddDays(-90)
    $userproperty
    }
    $userlist

    ----------

    If it does, please accept the answer and upvote, please do comment if something seems a bit off.


  2. Rich Matheisen 47,896 Reputation points
    2022-12-09T16:33:39.7+00:00

    In one of your earlier posts I gave you an answer to how to add users whose password hadn't been changed in 4 months to the group "BannedUsers" (how-to-create-powershell-list-accounts-last-passwo.html).

    Given that earlier answer, the members of the group "BannedUsers" would already meet your criteria -- except the users would be found in two different groups (BannedUsers, and Leavers). Is that what you want? Or is there more to your question than what you've stated? If the "two group" requirement is what you want to so, just add another "Add-ADGroupMember" to the script.

    0 comments No comments

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.