-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSetForwardingAddressENS.ps1
78 lines (71 loc) · 2.6 KB
/
SetForwardingAddressENS.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
67
68
69
70
71
72
73
74
75
76
77
78
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$InputFile
)
BEGIN {
$global:ErrorActionPreference = "Stop"
If (-not (Test-Path $InputFile)) {
Write-Host "File $InputFile does not exist. Exiting." -ForegroundColor Red
exit
}
If (-not $InputFile.EndsWith('.csv')) {
Write-Host "File $InputFile does not end with '.csv'. Exiting." -ForegroundColor Red
exit
}
$Mailboxes = Import-Csv -LiteralPath $InputFile
$DATE = Get-Date -Format yyyy-MM-dd_HH.mm
$ErrorFile = "Email_Forwarding_Address_Errors_$DATE.csv"
function SetForwardingAddresses($Mailboxes) {
$Total = $Mailboxes | Measure-Object | Select-Object -ExpandProperty Count
$i = 0
$ErrorCount = 0
$ErrorList = @()
foreach ($User in $Mailboxes) {
Write-Progress -Id 1 -Activity "Setting forwarding addresses..." -Status "Mailboxes: [$i/$Total] | Errors: $ErrorCount" -PercentComplete ($i / $Total * 100)
$i++
$Source_Email = $User."Source_Email"
$Target_Email = $User."Target_Email"
Try {
$Mailbox = Get-Mailbox $Source_Email
if (($Mailbox | Measure-Object | Select-Object -ExpandProperty Count) -ne 1) {
Throw "Invalid mailbox count."
}
}
Catch {
$err = $_
$User | Add-Member -MemberType NoteProperty -Name Error -Value $err
Write-Host "Error getting mailbox $Source_Email. Error: $err" -ForegroundColor Red
$ErrorCount += 1
$ErrorList += $User
Continue
}
Try {
Set-Mailbox $Source_Email -DeliverToMailboxAndForward $true -ForwardingSMTPAddress $Target_Email
Write-Verbose "Set forwarding address for $Source_Email to $Target_Email"
}
Catch {
$err = $_
$User | Add-Member -MemberType NoteProperty -Name Error -Value $err
Write-Host "Error getting mailbox $Source_Email. Error: $err" -ForegroundColor Red
$ErrorCount += 1
$ErrorList += $User
Continue
}
}
if ($ErrorList) {
$ErrorList | Export-Csv -NoTypeInformation -Append -LiteralPath $ErrorFile
}
}
}
PROCESS {
Write-Verbose "Working on user mailboxes..."
if ($Mailboxes) {
SetForwardingAddresses -Mailboxes $Mailboxes
}
else {
Write-Host "No user mailboxes in CSV file." -ForegroundColor Cyan
}
}
END {}