metho
metho

Reputation: 73

Powershell Active Directory Users to Multiple Groups using CSV

I'm trying to assign Groups to users in Active Directory. In a simple case, its just case for doing a loop through a CSV file. However, In my circumstances, My csv is different. Example of csv is as followed.

tjone,Time,Jones,Time Jones,[email protected],Time Jones,Home Work, Manager, Finance, Staff, "OU=Groups,DC=Home,DC=ac,DC=uk",Finance;HR,P@ssw0rd

The Script is as followed:

#Read the CSV file
$PathofCSV = "C:\Users\Administrator\Desktop\users.csv"

$Header = "sAMAccountName","givenName","sn","DisplayName","mail","cn","Company","Title","Department","OrgUnit","OU","Groups","Password"

$InfoCSV = import-csv $PathofCSV -Delimiter "," -Header $Header

ForEach ($user In $infoCSV)

{
Add-ADGroupMember -Identity $user.Groups -Members $user.sAMAccountName
}   

This is slightly different as you can see I'm trying to process the Groups Column which has more than one name and to make the matter worse, they are separated by the ";". So when I run the script, it see two name as one.

Question is, is it possible to separate those two names and processing them i.e. assigning two or more group names from one column.

I'm in an unfortunate position as I can't change the csv which I have received.

Any sort of help world be appreciated.

Upvotes: 0

Views: 1235

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

As has already been pointed out in comments, use the -split operator:

foreach($user in $infoCSV)
{
    foreach($group in $user.Groups -split ';')
    {
        Add-ADGroupMember -Identity $group -Members $user.sAMAccountName
    }
}

If this is PowerShell 2.0 (-split was introduced in version 3.0), you can use the String.Split() method:

foreach($user in $infoCSV)
{
    foreach($group in $user.Groups.Split(';'))
    {
        Add-ADGroupMember -Identity $group -Members $user.sAMAccountName
    }
}

Upvotes: 1

Related Questions