none
Powershell script to check and add users to Group from csv file RRS feed

  • Question

  • Hello,

    I'm trying to put together a  PowerShell script that can do the following:

    1. Read a CSV file

    2. Check to see if user is in security group (If it's not, add to group and if it is, then leave as is and continue w/ next users)

    3. Have some type of error checking

    I have seen the following script and it works but if the user is ALREADY part of the group, it will error out and not add new users:

    Import-module ActiveDirectory Import-CSV "C:\Users.csv" | % { Add-ADGroupMember -Identity TestGroup1 -Member $_.UserName } 

    So I'm thinking modifying the above to have some type of decision control structure shall do the trick but I lack the actual skill to put something together. Can someone be kind enough and share some ideas/thoughts/possible solutions?

    Friday, August 16, 2013 4:37 PM

All replies

  • Hello,

    Try this script , it is working fine for me .

    foreach ( $user in (Import-Csv .\users.csv | select -ExpandProperty identity))
    {
    $u = (Get-ADUser -Identity $user).distinguishedName
    $g = Get-ADGroupMember -Identity "TestGroup"| select -ExpandProperty distinguishedname
    If ( $g -contains $u ) {
        Write-Host " $user already exists in this group"
    }
    Else {
       Add-ADGroupMember testgroup -Members $u
       write-host " $user added to $group group successfully "

    } }

    Note : My csv file contains list of  SamaccountName of users. it is like below and saved in C: drive and I am running this script from C: drive.

    Identity

    user1

    user2

    user3

    ... and so on

       

    Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you.

    Saturday, August 17, 2013 4:04 PM
  • Hello,

    We found one problem with above script given by me , if we want to add users to different group other than group which is in script's code , we have to change group name every time.

    So to solve this problem we have create a Custom function  , in which we can supply desired group name as parameter of function. Doing this there is no need to change the group name in script's code .

    For this purpose I have create a article which describes in detail . 

    Please look here for  article.



    Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you.

    Sunday, August 18, 2013 9:07 AM
  •  

    Hello jhurtado05,

    Any update please ?

    Have you tried script ?


    Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you.

    Thursday, August 22, 2013 6:59 AM