/
Remove-Domain.ps1
66 lines (51 loc) · 1.75 KB
/
Remove-Domain.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<#
.SYNOPSIS
This script removes a single email domian (domain.com) for all mailboxes in an Office 365 tenant.
.DESCRIPTION
Domain is a required parameter
.PARAMETER Domain
Required paramter. Domain to be removed from all mailboxes in tenant.
.NOTES
1.0 -
Remove-Domain.ps1
v1.0
5/20/2020
By Nathan O'Bryan, MVP|MCSM
nathan@mcsmlab.com
.EXAMPLE
Remove-Domain -Domain domain.com
.LINK
https://www.mcsmlab.com/about
https://github.com/MCSMLab/
#>
#Command line parameter
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True)][String]$Domain
)
Clear-Host
If ($exscripts)
{
Write-Host 'Exchange Management Shell loaded'
}
Else
{
Write-Host 'Connecting to Exchange Online PowerShell'
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
}
$RemoveSMTPDomain = "smtp:*@$Domain"
$AllMailboxes = Get-Mailbox -ResultSize Unlimited | Where-Object {$_.EmailAddresses -clike $RemoveSMTPDomain}
ForEach ($Mailbox in $AllMailboxes)
{
$i = $i+1
Write-Progress -Activity "Removing $Domain from all mailboxes" -Status "For $Mailbox" -PercentComplete ($i/$AllMailboxes.count*100)
$AllEmailAddress = $Mailbox.EmailAddresses -cnotlike $RemoveSMTPDomain
$RemovedEmailAddress = $Mailbox.EmailAddresses -clike $RemoveDomainsmtp
$MailboxID = $Mailbox.PrimarySmtpAddress
$MailboxID | Set-Mailbox -EmailAddresses $AllEmailAddress #-whatif
Write-Host "The follwoing E-mail address where removed $RemovedEmailAddress from $MailboxID Mailbox "
}
Write-Host "Done! Removing connection to Exchange Online"
Remove-PSSession $Session