Gaterde
Gaterde

Reputation: 819

Convert E-Mail Address to SamAccountName

I have a csv like this:

Group;User
TestGroup1;[email protected]
TestGroup2;[email protected]

Now I want to add the Group to the User. I cant add them by the mail address so I have to get the SamAccountName. This is what I've come up with:

Import-module ActiveDirectory

foreach ($item in (Import-CSV users.csv -delimiter ";"))
{
    $userMail = $item.("User")
    $userSAM = Get-ADUser -Filter {mail -eq $userMail} -Properties SamAccountName
    Write-Host $item.("Group") $userSAM
}

But the Variable "UserSAM" stays emtpy.

Upvotes: 0

Views: 1911

Answers (1)

Hickinsauce
Hickinsauce

Reputation: 28

This should return just the usernames which you can use to add the user to the group.

Import-Module ActiveDirectory
foreach ($item in (Import-CSV users.csv -Delimiter ";")) {
      $userMail = $item.User
      $userSAM = Get-ADUser -Filter {mail -eq $userMail} | Select-Object -ExpandProperty SamAccountName
      Write-Host $item.Group $UserSAM
}

If this returns what you need just add this line into the end of the loop:

    Add-ADGroupMember -Identity $item.Group -Members $UserSAM

Upvotes: 1

Related Questions