Get users in an AD-group and mail the content

Today I got a question if could write a small script to get users in an AD-group and mail the content to the service-desk. (Easy way to keep track of licenses for O365 for example)
The complete script can be found in the bottom of this post.

This script can easily be added to a scheduled task that will run once every week or more often depending on your needs.

The first thing we need is an array to hold all the users in the AD-group.

$users = @()

Next, we need to get the members of the group

$group = Get-ADGroupMember "<GroupName>"

The main part of the script is a loop that adds the members of the AD-group to the array, and in my case, only selects the name of the users.

foreach($member in $group){
    $users += $member.name
}

Then we count how many objects we have and format the content of the array so we get each user on its own line.

$count = $group.Count
$ftUsers = $users -join "`n"

Then we use “Send-MailMessage” to send all the information we’ve selected to the recipient.

Send-MailMessage -to "user1 <user01@mail.com>" -from "User2 <user2@mail.com>" -Subject "Subject of mail" -Body "Group <insert name> contains $($count) users.`n$($ftUsers)"

The complete script, including the import of ActiveDirectory module.

Import-Module ActiveDirectory
$users = @()
$group = Get-ADGroupMember "<GroupName>"

foreach($member in $group){
    $users += $member.name
}

$count = $group.Count
$ftUsers = $users -join "`n"

Send-MailMessage -to "user1 <user01@mail.com>" -from "User2 <user2@mail.com>" -Subject "Subject of mail" -Body "Group <insert name> contains $($count) users.`n$($ftUsers)"
This entry was posted in Powershell and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *