none
Import group and members csv to AD RRS feed

  • Question

  • I have csv format:

    cn; memberuid
    group1; username1 / username2 | username3 | username4

    I'm trying to import it into an AD script:

    import-Csv C:\import-Csv\test.csv | ForEach {
    $cn = $_.Group
    $memberuid = $_.User

        try {

            Add-ADGroupMember -Identity $cn -Members $user -ErrorAction Stop

        } catch {

            New-ADGroup ...
            Add-ADGroupMember ...

        }

    }

    But that something is not working

    Friday, October 25, 2019 3:43 PM

Answers

  • Your CSV content should be like below:

    cn, memberuid
    group1, username1
    group1, username2
    group1, username3
    group2, username1
    group2, username4

    And your script should be like below:

    Import-Csv "C:\import-Csv\test.csv" | ForEach-Object {
    $cn = $_."cn"
    $memberuid = $_."memberuid"
    Add-ADGroupMember -Identity $cn -Members $memberuid
    }

    Saturday, October 26, 2019 5:37 AM
  • Hint:

    Drop all of the unnecessary quotes an interim variables.  Direct use of the csv is the preferred method.

    Import-Csv C:\import-Csv\test.csv |
        ForEach-Object {
            Add-ADGroupMember -Identity $_.cn -Members $_.memberuid
        }

    See: The PowerShell Best Practices and Style Guide


    \_(ツ)_/

    Saturday, October 26, 2019 5:50 AM

All replies

  • Your file is not a CSV file that can easily be used. You will have to split the names into an array.

    Also you are not referencing the CSV correctly.

    See:
    help import-csv -online

    Read and understand the examples.


    \_(ツ)_/

    Friday, October 25, 2019 5:18 PM
  • Your CSV content should be like below:

    cn, memberuid
    group1, username1
    group1, username2
    group1, username3
    group2, username1
    group2, username4

    And your script should be like below:

    Import-Csv "C:\import-Csv\test.csv" | ForEach-Object {
    $cn = $_."cn"
    $memberuid = $_."memberuid"
    Add-ADGroupMember -Identity $cn -Members $memberuid
    }

    Saturday, October 26, 2019 5:37 AM
  • Hint:

    Drop all of the unnecessary quotes an interim variables.  Direct use of the csv is the preferred method.

    Import-Csv C:\import-Csv\test.csv |
        ForEach-Object {
            Add-ADGroupMember -Identity $_.cn -Members $_.memberuid
        }

    See: The PowerShell Best Practices and Style Guide


    \_(ツ)_/

    Saturday, October 26, 2019 5:50 AM
  • Also, note that the groups must be identified by distinguishedName or sAMAccountName (or SID or GUID, but that is not convenient). And the members must be identified by distinguishedName or sAMAccountName. The Name attribute (the value of the cn attribute) does not uniquely identify the object, and is not accepted by the cmdlet (unless it matches the sAMAccountName).

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Friday, November 1, 2019 1:55 PM
    Moderator