Add users to an Active Directory group based on user attributes

A while back I visited a company to help install Specops Password Reset. They wanted a Group Policy configured for password resets using SMS to be applied to users with a corporate mobile phone. All other users should be reached by a Group Policy configured for password resets using security questions.

The best way to make this work is to filter the SMS Group Policy to a security group and make sure this GPO is in top of the Link order. So far so good right?

No, not really. This customer has thousands of users so manually handling this security group wasn’t an option.

To solve the problem I wrote this short PowerShell script and put it in Task Scheduler to run once a night. What the script does is check the Mobile attribute on all users. Any user that has something in this attribute (hopefully a mobile number) will be a member of the security group. The script will also take a look in the security group to find the users whose mobile numbers have been erased from the attribute and removes those users from the group.

Here is the script:

Import-Module ActiveDirectory
Get-ADGroupMember -Identity "SPR SMS Users" | Get-ADUser -Properties Mobile | Where-Object {$_.Mobile -eq $null} | % {Remove-ADGroupMember -Identity "SPR SMS Users" -Members $_ -Confirm:$false}
Get-ADUser -SearchBase 'OU=Users,OU=CORP,DC=domain,DC=local' -filter {mobile -ne "$null"} | % {Add-ADGroupMember "SPR SMS Users" $_.SamAccountName}

Now you too can add users to an Active Directory group based on user attributes. For more tips on using PowerShell with Specops Password Reset check out this blog post Customer Attribute Mobile.

(Last updated on October 30, 2023)

Tags: , , ,

mikael ingelin

Written by

Mikael Ingelin

Product specialist from Stockholm, Sweden has worked in the IT industry for over 25 years. For the past 10 years he has been working at Specops Software and before this he was responsible for the complete IT infrastructure at one of Sweden’s largest law firms. He has a broad practical and theoretical experience of managing, architecture and deploying complex IT infrastructures. Extensive knowledge of virtualization, Windows Server, Windows security, Active Directory and Group Policy.

Back to Blog