Leaver Script - Record AD groups and email them before changing group members


I have a leaver’s script that emails a summary into the support ticket about the leaver that was disabled. I’d like to add a part that emails the AD group membership of that user (so we have it in the ticket) and then removes their AD group membership. I’ve managed to get it working but the email is very hard to read. The script is below.

Even though I’m using the format-table command at the end of the adgroups variable, it doesn’t carry across into the email.
The email I get through is like the following, but I’d like it to be formatted better: https://snipboard.io/ai1rL4.jpg

Is there any way I can achieve this?

Thanks in advance for your help.


Write-Host -ForegroundColor Yellow "Enter your Office 365 details"

$CloudCredential = Get-Credential

$ulist = Import-Csv C:\Operations\Starters-Leavers\leavers.csv
$LeaversOU = 'OU=LeaversPending,OU=Azure,DC=domain,DC=domain'
$PermLeaversOU = 'OU=Leavers,OU=domain Others,DC=domain,DC=domain'

# Connect to Office 365 / Outlook Live
$CloudSessionParameters = @{
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = 'https://outlook.office365.com/Powershell'
Credential = $CloudCredential
Authentication = 'Basic'
AllowRedirection = $true
WarningAction = 'SilentlyContinue'
$CloudSession = New-PSSession @CloudSessionParameters
Import-PSSession $CloudSession -Prefix Cloud

#Connect to local Exchange
$LocalExchangeSessionParameters = @{ 
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = 'http://serverexch1/Powershell/'
Authentication = 'Kerberos'

$LocalExchangeSession = New-PSSession @LocalExchangeSessionParameters
Import-PSSession $LocalExchangeSession

###### PART 1 ######

$ulist | ForEach-Object {

try {
# ErrorAction is important to catch the error
$adacct = Get-ADUser $_.user -Properties Name, SamAccountname, UserPrincipalName, CanonicalName, Enabled, EmailAddress, PasswordExpired, Modified -ErrorAction Stop
} catch {
Write-Error "User $($_.user) does not exist, cannot disable"
Add-Content -Path C:\Operations\Starters-Leavers\UsersNotProcessed.log -Value $_.user
# Skips to the next user in $ulist, does not disable anything

$body = Get-CloudMailbox -Identity $adacct.UserPrincipalName | Select-Object Name, Alias, EmailAddresses -ExpandProperty EmailAddresses

$report = $adacct | Select-Object Name, SamAccountname, UserPrincipalName, CanonicalName, EmailAddress, PasswordExpired, Modified | Out-String

Write-Host -ForegroundColor Yellow "Taking note of all AD groups to email into the ticket"
$adgroups = Get-AdPrincipalGroupMembership -Identity $_.user | Where-Object -Property Name -Ne -Value 'Domain Users' | ft name

Write-Host -ForegroundColor Yellow "Disabling user account on AD"
Disable-ADAccount -Identity $adacct.SamAccountName
Write-Host -ForegroundColor Green "Disabled AD account"
# Move-ADObject -Identity $adacct.DistinguishedName -TargetPath $LeaversOU

Write-Host -ForegroundColor Yellow "Removing the leaver from all AD groups except Domain Users"
Get-AdPrincipalGroupMembership -Identity $_.user | Where-Object -Property Name -Ne -Value 'Domain Users' | Remove-AdGroupMember -Members $adacct.UserPrincipalName
Write-Host -ForegroundColor Green "Removed from all AD groups except Domain Users"

Write-Host -ForegroundColor Yellow "Changing AD Password to Random Password"
$Pwd = -join ((48..122) | Get-Random -Count 16 | ForEach-Object { [char]$_ })
$PwdSecStr = ConvertTo-SecureString $pwd -AsPlainText -Force
Set-ADAccountPassword -Identity $adacct.SamAccountName -NewPassword $PwdSecStr -Reset
Write-Host -ForegroundColor Green "Password changed for $($adacct.Name)"

###### PART 2 ######

### Get AD user details again as the user has moved OU
$adacct = Get-ADUser $_.user
$ticket = $_.ticket

### Disable mailbox, move user to Leavers OU (domain/Leavers)

Write-Host -ForegroundColor Yellow "Disabling Remote Mailbox"
Disable-RemoteMailbox -Identity $adacct.SamAccountName -Confirm:$false
Write-Host -ForegroundColor Green "Remote Mailbox disabled"
Write-Host -ForegroundColor Yellow "Now moving user to Leavers AD OU"
Move-ADObject -Identity $adacct.DistinguishedName -TargetPath $PermLeaversOU
Write-Host -ForegroundColor Green "Moved to Leavers OU"

$report1 = $adacct | Select-Object Enabled | Out-String

Write-Host -ForegroundColor Yellow "Generating and sending user status report directly into ticket"

#Sends SMTP email via o365 smtp relay
$sendMailMessageSplat = @{
Subject = "[#INC-$($_.ticket)]"
From = 'LeaverPSScriptreport@domain.com'
To = 'test@domain.com'
SmtpServer = 'domain-com.mail.protection.outlook.com'
Body = $report + $report1 + $body + $adgroups
Send-MailMessage @sendMailMessageSplat


format table really just changes from objects to a view for the console.

try replacing |ft name with |select-object name


Have you considered using the EnhancedHTML2 module? There’s a bit more work to get the formatting you want but there’s a lot more you can do.

What David said is probably what’s going on. But the output doesn’t completely match what you’re trying to do, either, and that was messing with me.

This line is pushing only the “EmailAddresses” attribute for the mailbox for $adacct.UserPrincipalName. It doesn’t output the “Name” and “Alias” attributes. That has to do with the -ExpandProperty parameter and the way it’s treated, I think.

$body = Get-CloudMailbox -Identity $adacct.UserPrincipalName | Select-Object Name, Alias, EmailAddresses -ExpandProperty EmailAddresses

If you want all 3, you’ll have to put them into separate variables or you’ll have to do some other manipulation before you dump it to an email.

And I’m still not sure what’s going on with the way it’s displaying $adgroups… It looks like the istinguishedName attributes are showing up in the email, even though it should be the Name attributes. But the line that David posted should give you a list containing the names of the groups that user is a member of. You may have to add “| Out-String” to the end of his line to make it work with your concatenation.

And I was thinking about going with some kind of HTML output, but if he is trying to send this to a ticketing system, it probably only supports text as notes. If you can use HTML, Aaron is right. You can do a lot more and make it quite a bit more readable.

Hi all,

Thanks for your help. It still didn’t work with the changes but I changed the way I was going to do this slightly. Instead of formatting it in the email, I had the AD groups output to a text file that was then attached in the email. That gives me exactly what I need.

Thanks again,


If you’re wanting to keep email content in the script, a here-string works for me. It will preserve the formatting.

$emailBody = @"


$($adgroups | Out-String)

Assign $emailBody to Body in the splat.