none
Powershell - script to add user to security group if user does not already exist

    Question

  • Hi Everyone,

    I'm not too good when it comes to writing powershell scripts, but hopefully someone could be kind enough to either point me in the right direction, or (if you really feel like it) write the script for me! ^_^

    Currently I have a GPO in place with which we disable local logons and via Terminal Services for our Service Accounts in AD. The GPO stops this via a Security Group which contains our service accounts.

    At the moment, when we create a new service account, we need to add the account to the security group (a manual process obviously).

    What I would like to do is to automate this process by:

    • Use a powershell script to search for service accounts in active directory that matches a naming convention (e.g. _svcAPACxxx), and compare this list with the membership of the security group listed in the GPO.
    • If the account does not exist as a member of the group, add account to group. If it already exists, great!

    I would look to set this up via a scheduled task, and send an e-mail as to a DL as to whether accounts were added at the last run point (and which accounts were added at the time).

    Wednesday, July 17, 2013 3:00 AM

Answers

  • Using AD Module:

    $groupName = 'MyTestGroup'
    $currentGroupMembers = Get-ADGroupMember -Identity:$groupName | ? { $_.objectClass -ieq 'user' } | Select-Object -ExpandProperty 'samAccountName'
    Get-ADUser -Filter { samAccountName -like '_svcAPAC*' } | ? { $currentGroupMembers -inotcontains $_.samAccountName } | Add-ADPrincipalGroupMembership -MemberOf:"$groupName"

    The above code is untested.

    There are probably more efficient ways to do this but this code should be the simplest possible.

    Wednesday, July 17, 2013 6:12 AM

All replies

  • Using AD Module:

    $groupName = 'MyTestGroup'
    $currentGroupMembers = Get-ADGroupMember -Identity:$groupName | ? { $_.objectClass -ieq 'user' } | Select-Object -ExpandProperty 'samAccountName'
    Get-ADUser -Filter { samAccountName -like '_svcAPAC*' } | ? { $currentGroupMembers -inotcontains $_.samAccountName } | Add-ADPrincipalGroupMembership -MemberOf:"$groupName"

    The above code is untested.

    There are probably more efficient ways to do this but this code should be the simplest possible.

    Wednesday, July 17, 2013 6:12 AM
  • Thanks,

    I will give this a try and see how it goes. Will let you know later.

    Thanks again!

    Thursday, July 18, 2013 8:12 AM