Last active
November 12, 2019 00:03
-
-
Save kevinblumenfeld/b2f746207c8a4fccace5171ae0554c9c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Remove-TenantAddress { | |
<# | |
.SYNOPSIS | |
Remove all mailbox addresses with one more more domains/words | |
.DESCRIPTION | |
Remove all mailbox addresses with one more more domains/words | |
.PARAMETER Domains | |
List of domains or words to find in the email addresses | |
.EXAMPLE | |
Remove-TenantAddress -Domains 'fabrikam.com' | Export-Csv c:\scripts\log.csv -NoTypeInformation | |
.EXAMPLE | |
Remove-TenantAddress -Domains 'wingtip.com|fabrikam.com|widget.com' | Export-Csv c:\scripts\log.csv -NoTypeInformation | |
.NOTES | |
Connect to Exchange Online Version 2 | |
Connect-CloudMFA -Tenant contoso -EXO2 | |
#> | |
param ( | |
[Parameter(Mandatory)] | |
$Domains | |
) | |
end { | |
$EA = $ErrorActionPreference | |
$ErrorActionPreference = 'Stop' | |
$RemoveList = Get-EXOMailbox -ResultSize Unlimited | Select-Object @( | |
'DisplayName' | |
'PrimarySmtpAddress' | |
'UserPrincipalName' | |
@{ | |
Name = 'EmailList' | |
Expression = { | |
$_.emailaddresses | Where-Object { | |
@($_ -match ([Regex]::Escape($Domains))) | |
} | |
} | |
} | |
'ExchangeGuid' | |
'Guid' | |
) | |
$RemoveList = $RemoveList.Where{ $_.EmailList } | |
foreach ($Remove in $RemoveList) { | |
try { | |
Write-Host "$($Remove.DisplayName)" -ForegroundColor White | |
Get-EXOMailbox -Identity $Remove.Guid | Set-Mailbox -EmailAddresses @{Remove = @($Remove.EmailList) } | |
Write-Host "$($Remove.DisplayName) Removed" -ForegroundColor Green | |
[PSCustomObject]@{ | |
Action = "REMOVEEMAILS" | |
DisplayName = $Remove.DisplayName | |
PrimarySmtpAddress = $Remove.PrimarySmtpAddress | |
UserPrincipalName = $Remove.UserPrincipalName | |
Guid = $Remove.Guid | |
Result = "SUCCESS" | |
Log = "SUCCESS" | |
Remove = @($Remove.EmailList -ne '' -Join '|') | |
} | |
} | |
catch { | |
Write-Host "$($Remove.DisplayName) $($_.Exception.Message)" -ForegroundColor Red | |
[PSCustomObject]@{ | |
Action = "REMOVEEMAILS" | |
DisplayName = $Remove.DisplayName | |
PrimarySmtpAddress = $Remove.PrimarySmtpAddress | |
UserPrincipalName = $Remove.UserPrincipalName | |
Guid = $Remove.Guid | |
Result = "FAILED" | |
Log = $_.Exception.Message | |
Remove = @($Remove.EmailList -ne '' -Join '|') | |
} | |
} | |
} | |
$ErrorActionPreference = $EA | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment