Tuesday 21 February 2017

Add AD users to group, based on email address

This is a short script I wrote to add a user account to a group, using only the email address associated with the account.

As a side note, this is my first post of the year so perhaps a 'Happy New Year!' is required?!!

To use the script, modify $DC, $users and $group. Remember that $users should point to a text file containing mail addresses, if you wish to use it as I did.
       

# Import AD Module

Import-Module ActiveDirectory

# Get Credentials

$Creds = Get-Credential -Credential "$env:USERNAME"

# Domain Controller to use

$DC = "some.dc.network"

# Path to text file containing usernames to be added to the group
$Users = Get-Content "\\here\are\my\users.txt"

# Group name to add users to
$Group = "Some Group"


# Add users to the group
foreach ($user in $users){
write-host -fore white "Finding user.."
$FoundUser = Get-ADUser -Filter {EmailAddress -eq $user} -Credential $Creds
write-host -fore white "Adding $user to $group"
Try{
Add-ADGroupMember $group $founduser.sid -Credential $Creds -server $DC}
Catch {
write-host -fore Red "Failed to add $user to $group"
}

       
 

No comments:

Post a Comment

PerfC Vaccination for ExPetr/Petya/NotPetya Wiper

This is a script I've written to 'vaccinate' our domain against the ExPetr/Petya/NotPetya Wiper. In short, it finds all comput...