Exchange.psm1

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
#region Types
add-type @'
namespace CPolydorou.Exchange
{
    public class GroupMembership
    {
        public string Group;
        public string Object;
        public bool Member;
        public string GroupDN;
        public string ObjectDN;
    }
}
'@

#endregion

#region Functions

#region Get-PublicFolderReplicationStatus
function Get-PublicFolderReplicationStatus
{
    <#
        .SYNOPSIS
        Checks the replication status of Exchange Public Folders.
 
        .DESCRIPTION
        The Get-PublicFolderReplicationStatus cmdlet checks the item count of a Public Folder and it's subfolders on two replicas and compares the item count on each folder.
     
        .PARAMETER TopLevelPublicFolder
        Specifies the path to the Public folder.
 
        .PARAMETER ReferenceServer
        Specifies the name of the server that is going to be used as source.
 
        .PARAMETER DifferenceServer
        Specifies the name of the server that is going to be compared to the source server.
 
        .PARAMETER IncompleteOnly
        When this parameter is used, only the Public Folders with different item counts are displayed.
 
        .INPUTS
        None. You cannot pipe objects to Get-PublicFolderReplicationStatus
 
        .OUTPUTS
        Get-PublicFolderReplicationStatus creates a table that contains the paths of the Public folders and the item count on each server.
 
        .EXAMPLE
        Get-PublicFolderReplicationStatus -TopLevelPublicFolder "\PublicFolder" -ReferenceServer ExchangeServer1 -DifferenceServer ExchangeServer2 -IncompleteOnly
 
        This command will compare the item count of the "PublicFolder" public folder and it's subfolders on the ExchangeServer1 and ExchangeServer2 servers and will display only the folder where the item count is not the same.
 
        .NOTES
        This is an one way check. In order to verify the replication, please run the same command using the refference server as source and vice versa.
    #>


    Param
    (
        [string]$TopLevelPublicFolder,
        [string]$ReferenceServer,
        [string]$DifferenceServer,
        [switch]$IncompleteOnly
    )

    Begin {}

    Process
    {

        # Get the public folders from both servers
        $publicfoldersref = Get-PublicFolder -ResultSize unlimited -Recurse -Server $ReferenceServer -Identity $TopLevelPublicFolder 
        $publicfoldersdif = Get-PublicFolder -ResultSize unlimited -Recurse -Server $DifferenceServer -Identity $TopLevelPublicFolder 

        foreach($pf in $publicfoldersref)
        {
            # TODO
            # Test if public folder exists on both servers

            # Compare statistics
            $StatisticsRef = Get-PublicFolderStatistics -Identity $pf.Identity -Server $ReferenceServer -ResultSize unlimited
            $StatisticsDif = Get-PublicFolderStatistics -Identity $pf.Identity -Server $DifferenceServer -ResultSize unlimited

            $obj = New-Object psobject
            $obj | Add-Member -MemberType NoteProperty -Name Parent -Value $pf.ParentPath
            $obj | Add-Member -MemberType NoteProperty -Name Name -Value $pf.Name
            $obj | Add-Member -MemberType NoteProperty -Name ReferenceCount -Value $StatisticsRef.itemcount
            $obj | Add-Member -MemberType NoteProperty -Name DifferenceCount -Value $StatisticsDif.itemcount

            if( $IncompleteOnly )
            {
                if( $StatisticsRef.ItemCount -ne $StatisticsDif.ItemCount)
                {
                    $obj
                }
                else
                {
                    continue
                }
            }
            else
            {
                $obj
            }
        }
    }

    End {}
}
#endregion

#region Get-SendOnBehalfPermission
Function Get-SendOnBehalfPermission
{
    <#
        .SYNOPSIS
        Gets the recipients that have send on behalf permission.
 
        .DESCRIPTION
        The Get-SendOnBehalfPermission cmdlet returns a list of all the recipients that have Send On Behalf permission.
     
        .PARAMETER Identity
        The Identity of the recipient on which the permissions are set.
    #>


    Param
    (
        [Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter]$Identity
    )

    $recipient = Get-Recipient $Identity

    if($recipient.recipienttype -like "*Mailbox")
    {
        $delegates = (Get-Mailbox $recipient.Identity).GrantSendOnBehalfTo
        $delegates |
            Get-Recipient
    }

    if($recipient.recipienttype -like "*Group")
    {
        $delegates = (Get-DistributionGroup $Recipient.Identity).GrantSendOnBehalfTo
        $delegates |
            Get-Recipient
    }
}
#endregion

#region New-TerminationInboxRule
Function New-TerminationInboxRule
{
<#
    .SYNOPSIS
    Creates a new termination inbox rule.
 
    .DESCRIPTION
    The New-TerminationInboxRule cmdlet creates an inbox rule that replies to everyone that sends a message on the mailbox.
     
    .PARAMETER Identity
    The identity of the mailbox
 
    .PARAMETER URL
    The EWS URL, usually is https://mail.domain.com/EWS/Exchange.asmx. If not specified, autodiscover will be used.
 
    .PARAMETER Credential
    The credentials to use. If not specified, the currently logged on user's credentials will be used. These credentials must belong to
    a user that has impersonation rights on the mailbox.
 
    .PARAMETER MessageSubject
    The subject of the reply.
 
    .PARAMETER MessageBody
    The body of the message.
 
    .PARAMETER RuleName
    The name of the rule to be created.
 
    .EXAMPLE
    [PS] C:\Windows\system32>New-TerminationInboxRule -Identity cpolydorou@lab.local -URL https://exchange2013a.lab.local/ews/exchange.asmx -RuleName "TestRule" -MessageSubject "Test Rule Subject" -MessageBody "Test Rule Body."
 
    [PS] C:\Windows\system32>Get-InboxRule -Mailbox cpolydorou
 
    Name Enabled Priority RuleIdentity
    ---- ------- -------- ------------
    TestRule True 1 2163278858382475265
#>


    [CmdletBinding()]
    Param
    (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Identity,

        [Parameter(Position = 1, Mandatory = $false)]
        [string]$URL,

        [Parameter(Position = 2, Mandatory = $false)]
        [PSCredential]$Credential,

        [Parameter(Position = 3, Mandatory = $true)]
        [string]$MessageSubject,

        [Parameter(Position = 4, Mandatory = $true)]
        [string]$MessageBody,

        [Parameter(Position = 5, Mandatory = $true)]
        [string]$RuleName = "Termination Auto Reply"
    )

    # Load Managed API dll
    try
    {
        Add-Type -Path ($psscriptroot + "\Microsoft.Exchange.WebServices.dll")
        Write-Verbose "EWS API Loaded."
    }
    catch
    {
        Write-Error "Could not locate the EWS API."
        return
    }

    # Get the mailbox
    try
    {
        $m = Get-Mailbox $Identity
    }
    catch
    {
        throw ("Could not find mailbox " + $Identity)
    }

    # Get the primary smtp address
    $PrimarySMTPAddress = $m.PrimarySMTPAddress

    # Set Exchange Version
    $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013 

    # Create Exchange Service Object
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion) 

    # Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
    if($Credential)
    {
        #Credentials Option 1 using UPN for the windows Account
        $creds = New-Object System.Net.NetworkCredential($Credential.UserName.ToString(),$Credential.GetNetworkCredential().password.ToString())    
        $service.Credentials = $creds
        Write-Verbose ("Using provided credentials (" + $Credential.UserName.ToString() + ").")
    }
    else
    {   
        #Credentials Option 2
        $service.UseDefaultCredentials = $true    
        Write-Verbose "Using current account."
    }

    if( $URL )
    {
        #CAS URL Option 1 Hardcoded
        $uri=[system.URI] $URL    
        $service.Url = $uri
        Write-Verbose ("Using CAS Server: " + $Service.url)
    }
    else
    {     
        #CAS URL Option 1 Autodiscover
        $service.AutodiscoverUrl($PrimarySMTPAddress,{$true})    
        Write-Verbose "Using Autodiscover."
    }

    # Set impersonation
    $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$PrimarySMTPAddress); 

    # Create the message template
    $templateEmail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
    $templateEmail.ItemClass = "IPM.Note.Rules.ReplyTemplate.Microsoft"
    $templateEmail.IsAssociated = $true
    $templateEmail.Subject = $MessageSubject
    $templateEmail.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody($MessageBody)
    $PidTagReplyTemplateId = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65C2, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
    $templateEmail.SetExtendedProperty($PidTagReplyTemplateId, [System.Guid]::NewGuid().ToByteArray())
    try
    {
        $templateEmail.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
        Write-Verbose "Created the message template."
    }
    catch
    {
        Write-Error ("Could not create the template:" + $_.Exception.Message)
        return
    }

    #Create Inbox Rule
    $inboxRule = New-Object Microsoft.Exchange.WebServices.Data.Rule
    $inboxRule.DisplayName = $RuleName
    $inboxRule.IsEnabled = $true
    $inboxRule.Conditions.SentToOrCcMe = $true
    $inboxRule.Actions.ServerReplyWithMessage = $templateEmail.Id
    $createRule = New-Object Microsoft.Exchange.WebServices.Data.CreateRuleOperation[] 1
    $createRule[0] = $inboxRule
    try
    {
        $service.UpdateInboxRules($createRule,$true)
        Write-Verbose "Successfully created the inbox rule."
    }
    catch
    {
        Write-Error ("Could not create the inbox rule: " + $_.Exception.Message)
        return
    }
}
#endregion

#region Test-DistributionGroupMember
Function Test-DistributionGroupMember
{
    <#
    .SYNOPSIS
 
    Test if an object is member of a distribution group.
    .DESCRIPTION
 
    The Test-DistributionGroupMember function will check if an object is member of a distribution group.
    .PARAMETER DistributionGroup
 
    The distribution group to check against.
    .PARAMETER Object
 
    The object to check.
     
    .PARAMETER Recurse
 
    Check for membership recursively
 
    .EXAMPLE
 
    Test-DistributionGroupMember -DistributionGroup distributionGroup -Object userEmail
     
    .EXAMPLE
 
    Get-DistributionGroup | Test-DistributionGroupMember -DistributionGroup distributiongroup@lab.local
 
    This command will get all the distribution groups and check if they are members of the distributiongroup@lab.local group.
 
    .EXAMPLE
 
    Get-Mailbox | Test-DistributionGroupMember -DistributionGroup distributiongroup@lab.local -Recurse
 
    This command will get all the mailboxes and check if they are members of the distributiongroup@lab.local group recursively (via nested groups).
 
    #>


    Param
    (
        [parameter(Mandatory=$true,Position=0)]
        [string]$DistributionGroup,

        [parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [string[]]$Object,

        [parameter(Mandatory=$false,Position=2)]
        [switch]$Recurse
    )

    Begin {}

    Process
    {
        foreach($o in $Object)
        {
            # Get the distribution group
            $group = New-Object PSObject
            try
            {
                $group = Get-DistributionGroup $DistributionGroup -ErrorAction Stop
            }
            catch
            {
                Write-Error ("Could not find the distribution group " + $DistributionGroup)
                return $null
            }

            # Get the recipient
            $recipient = New-Object PSObject
            try
            {
                $recipient = Get-Recipient $o -ErrorAction stop
            }
            catch
            {
                Write-Error ("Could not find a recipient for " + $o)
                return $null
            }

            # Query Active Directory
            $objectdn = $recipient.distinguishedname
            $groupdn = $group.distinguishedname
            if($Recurse)
            {
                $query = "(&(DistinguishedName=$objectdn)(memberOf:1.2.840.113556.1.4.1941:=$groupdn))"
            }
            else
            {
                $query = "(&(DistinguishedName=$objectdn)(memberof=$groupdn))"
            }
            # Query Active Directory
            $results = ([adsisearcher]$query).findall() 

            # Create the custom object
            $obj = New-Object CPolydorou.Exchange.GroupMembership
            $obj.Group = $group.Name
            $obj.Object = $recipient.Name

            if($results.Count -eq 0)
            {
                $obj.Member = $false
            }
            else
            {
                $obj.Member = $true
            }

            # Add the DNs of the group and the object
            $obj.GroupDN = $groupdn
            $obj.ObjectDN = $objectdn

            Write-Output $obj
        }
    }

    End {}
}
#endregion

#region Connect-Exchange
Function Connect-Exchange
{
    [cmdletbinding(DefaultParameterSetName=’SnapIn’)]
    
    Param
    (
        [parameter(Mandatory=$false, ParameterSetName = "SnapIn")]
        [switch]$SnapIn,

        [parameter(Mandatory=$false, ParameterSetName = "Implicit")]
        [switch]$Implicit,

        [parameter(Mandatory=$false, ParameterSetName = "Implicit")]
        [string]$Server = $env:COMPUTERNAME,

        [parameter(Mandatory=$false, ParameterSetName = "Script")]
        [switch]$Script
    )

        # if no switches have been selected connect using implicit remoting
        if($PSCmdlet.MyInvocation.BoundParameters.Count -eq 0)
        {
            $Session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri ("http://" + $Server + "/PowerShell") -Authentication Kerberos 
            Import-Module (Import-PSSession -Session $Session -DisableNameChecking) -Global -DisableNameChecking
            return
        }

        # Connect by adding the snapin
        if($SnapIn)
        {
            Add-PSSnapin *exchange*
            return
        }

        # Connect by implicit remoting
        if($Implicit)
        {
            $Session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri ("http://" + $Server + "/PowerShell") -Authentication Kerberos 
            Import-Module (Import-PSSession -Session $Session -DisableNameChecking) -Global -DisableNameChecking
            return
        }

        # Connect using the RemoteExchange.ps1 script
        if($Script)
        {
            # Get the path of the exchange installation folder
            #TODO: should check for versions later than 15 (2013) here
            $ExInstall = ""
            try
            {
                $ExInstall = (get-itemproperty HKLM:\SOFTWARE\Microsoft\ExchangeServer\V15\Setup).MsiInstallPath
            }
            catch
            {
                Write-Error "Could not locate the excange home directory."
                return
            }
            $scriptPath = $ExInstall + 'bin\RemoteExchange.ps1'
            . $scriptPath
            Connect-ExchangeServer -auto
            return
        }
}
#endregion

#region Move-ActiveMailboxDatabaseToPreference
Function Move-ActiveMailboxDatabaseToPreference
{
    <#
    .SYNOPSIS
 
    Activate Mailbox Database Copies using ActivationPreference.
    .DESCRIPTION
 
    The Move-ActiveMailboxDatabaseToPreference function will activate a database copy using it's activation preference number.
    .PARAMETER Server
 
    The name of the database.
 
    .PARAMETER TargetActivationPreference
 
    The activation preference number of the copy to be activated.
    .PARAMETER ShowOnly
 
    Only show the changes, not perform them.
    .EXAMPLE
 
    Move-ActiveMailboxDatabaseToPreference -Database DB001 -TargetActivationPreference 2
 
    This command will activate the copy of the database DB001 that has ActivationPreference 2.
    #>


    [cmdletbinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = 'High'
    )]

    Param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true, Position=0)]
        [Alias('Name')] 
        [String[]]
        $Database,

        [Parameter(Mandatory=$true,ValueFromPipeline=$false, Position=1)] 
        [int]$TargetActivationPreference,

        [switch]$ShowOnly
    )

    Begin{}

    Process
    {
        foreach($db in $Database)
        {
            if($PSCmdlet.ShouldProcess($db))
            {
                # Get the mailbox database
                New-Variable database -Force
                try
                {
                    $Database = Get-MailboxDatabase $db

                    # Get the database copies
                    $Copies = $database | Get-MailboxDatabaseCopyStatus

                    # Get the mounted copy
                    $mountedCopy = $Copies | Where-Object {$_.Status -eq "Mounted"}

                    # Find the copy we want to activate using the activation preference
                    $copyToActivate = $Copies | Where-Object {$_.ActivationPreference -eq $TargetActivationPreference}

                    # Check if the copy to activate exiss
                    if($copyToActivate -ne $null)
                    {
                        # Check the health of the copy and if it is lagged
                        if($copyToActivate.Status -ne "Healthy")
                        {
                            Write-Error "The copy to be activated is not in a healthy state."
                        }

                        if($copyToActivate.ReplayLagStatus -like "*Enabled:True*")
                        {
                            Write-Error "The copy to be activated is a lagged copy."
                        }

                        if($ShowOnly)
                        {
                            Write-Warning ("The copy " + $copyToActivate.Identity + " (ActivationPreference:" + $copyToActivate.ActivationPreference + ") will be activated.")
                        }
                        else
                        {
                            # Activate the copy
                            Move-ActiveMailboxDatabase -Identity $Database.Identity -ActivateOnServer $copyToActivate.MailboxServer
                        }
                    }
                    else
                    {
                        Write-Error "There is no database copy with preference $TargetActivationPreference for database $db"
                        continue
                    }
                }
                catch
                {
                    Write-Error "Could not find database $db."
                    continue
                }
            }
        }
    }

    End{}

}
#endregion

#region Rename-ExchangeShell
Function Rename-ExchangeShell
{
    <#
    .SYNOPSIS
 
    Set the title on the Exchange Shell window.
    .DESCRIPTION
 
    Set the title on the Exchange Shell window.
    .PARAMETER Title
 
    The new title.
    .EXAMPLE
 
    Rename-ExchangeShell -Title "Mailbox Query"
 
    This command will rename the current Exchange Shell to "Mailbox Query"
    #>


    Param
    (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Title
    )

    # Form the prompt function as a string
    $promptFunction = 'Function Global:Prompt{ $host.UI.RawUI.WindowTitle = "' + $Title + '"; Write-Host "[PS] " -NoNewLine -ForegroundColor Yellow; Write-Host (Get-Location).Path -NoNewLine; ">"}'

    # Create a scriptblock from that string
    $sb = [scriptblock]::Create($promptFunction)

    # Invoke the scriptblock
    Invoke-Command -ScriptBlock $sb
}
#endregion

#region Get-SendConnectorDomains
Function Get-SendConnectorDomains
{
    <#
    .SYNOPSIS
 
    Get the domains on each send connector.
    .DESCRIPTION
 
    The Get-SendConnectorDomains function will return all the domain names on each send connector and the respective cost.
    .PARAMETER Identity
 
    The identity of the connector to examine. If not specified, all connectors will be examined.
    .EXAMPLE
    Get-SendConnectorDomains
 
    This command will return all the domains configured on all send connectors.
 
    .EXAMPLE
    Get-SendConnectorDomains -Identity Internet
 
    This command will return all the domains configured on the "Intenet" send connector.
 
    .EXAMPLE
    Get-SendConnector -Identity "Test" | Get-SendConnectorDomains
 
    This command will return all the domains configured on the "Test" send connector.
    #>


    [cmdletBinding()]

    Param
    (
        [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$Identity
    )

    Begin
    {
        # Check if Exchange cmdlets are available
        try
        {
            Get-Command "Get-SendConnector" -ErrorAction Stop |
                Out-Null
        }
        catch
        {
            Throw "Could not find the Exchange cmdlets."
        }    
    }

    Process
    {
        # Get the send connectors
        Write-Verbose "Getting the send connectors"
        $connectors = @()

        # Get specific send connectors
        if($Identity)
        {
            foreach($sc in $Identity)
            {
                $connectors += Get-SendConnector -Identity $sc
            }
        }
        # Get all send connectors
        else
        {
            $connectors = Get-SendConnector
        }

        # Process each send connector
        foreach($sendC in $connectors)
        {
            Write-Verbose ("Processing send connector " + $sendC.Identity)

            # Get the string representation of the address space
            try
            {
                # This call will not fail if we are using implicit remoting
                $addressspacestring = $sendC.AddressSpaces.Split(',') 
            }
            catch
            {
                # if the above command fails, we are using the exchange shell
                # or have loaded the exchange snap in or binaries
                # Since the address spaces is an object, we are going to construct
                # the string representation
                $addressspacestring = @()
                $sendC.AddressSpaces |
                %{
                    $addressspacestring += $_.Type + ":" + $_.Address + ";" + $_.Cost
                }
            }

            # Parse each address space string and create custom objects
            $addressspacestring |
                %{
                    $start = $_.IndexOf(":") + 1
                    $end = $_.IndexOf(";")

                    $obj = New-Object -TypeName PSObject -Property @{
                                                                    'Domain' = $_.Substring($start, $end - $start)
                                                                    'Send Connector' = $sendC.Identity
                                                                    'Cost' = $_.Substring($end + 1, $_.Length - $end - 1)
                                                                   }

                    Write-Output $obj
                } |
                    Select-Object -Property 'Domain','Send Connector','Cost' |
                        Sort-Object -Property Domain
        }
    }

    End {}
}
#endregion

#region Get-MailboxDatabaseCopyThatShouldBeActive
Function Get-MailboxDatabaseCopyThatShouldBeActive
{
    <#
    .SYNOPSIS
 
    Get the mailbox database copies that have been moved from their home server.
    .DESCRIPTION
 
    The Get-MailboxDatabaseCopyThatShouldBeActive function will return all the mailbox database copies that are active and have an ActivationPreference value greater that 1.
    .PARAMETER Activate
 
    Activate the copies
    .EXAMPLE
 
    Get-MailboxDatabaseCopyThatShouldBeActive -Activate
 
    This command will get all the copies that should be activated and prompt to confirm the activation.
    #>


    [cmdletBinding(
        SupportsShouldProcess=$true,
        ConfirmImpact="High"
    )]

    Param
    (
        [switch]$Activate
    )

    Begin
    {
        # Check if Exchange cmdlets are available
        # Check for exchange cmdlets here
        try
        {
            Get-Command "Get-MailboxServer" -ErrorAction Stop |
                Out-Null
            Write-Verbose "Exchange cmdlets are available."
        }
        catch
        {
            Throw "Exchange cmdlets are not available. Please use the Exchange Management Shell."
        }
    }

    Process
    {
        # Examine all database copies
        Write-Verbose "Getting mailbox database copies."        
        $copies = Get-MailboxServer |
                    %{
                        Write-Verbose ("`tGetting copies from server " + $_.Name)
                        Get-MailboxDatabaseCopyStatus -Server $_.Name |
                            Where-Object { ($_.status -eq 'Mounted') -and ($_.ActivationPreference -gt 1)}
                    } |
                        %{
                            Get-MailboxDatabase $_.DatabaseName |
                                Get-MailboxDatabaseCopyStatus |
                                    Where-Object {$_.ActivationPreference -eq 1}                        
                        }

        # Prompt for activation
        if($Activate)
        {
            # Activate each copy
            foreach($c in $copies)
            {
                if ($PSCmdlet.ShouldProcess($c.Databasename, "Move-ActiveMailboxDatabase -ActivateOnServer " + $c.MailboxServer))
                {
                    Move-ActiveMailboxDatabase $c.DatabaseName -ActivateOnServer $c.MailboxServer |
                        Select-Object -ExcludeProperty RunspaceID  
                }
            }
        }
        else
        {
            # Return the copies
            $copies
        }
    }

    End {}
}
#endregion
#region Test-ExchangeImpersonation
function Test-ExchangeImpersonation
{
    <#
    .Synopsis
    Test the Exchange impersonation rights on a mailbox.
    .DESCRIPTION
    Test the Exchange impersonation rights on a mailbox.
    .EXAMPLE
        PS C:\> Test-ExchangeImpersonation -PrimarySMTPAddress test.mailbox@lab.local -Credential $cred -Action CreateDraft -Verbose -EWSUrl "https://mail.lab.local/ews/exchange.asmx"
        VERBOSE: Importing EWS library.
        VERBOSE: Using supplied credentials.
        VERBOSE: Connecting using EWS Url.
        VERBOSE: Creating message in drafts.
     
        Create an item in the test.mailbox@lab.local mailbox.
 
    .EXAMPLE
        PS C:\Users\administrator.LAB\Desktop> Test-ExchangeImpersonation -PrimarySMTPAddress test.mailbox@lab.local -Credential $cred -Action CreateSubfolder -Verbose
        VERBOSE: Importing EWS library.
        VERBOSE: Using supplied credentials.
        VERBOSE: Connecting using autodiscover.
        VERBOSE: Creating subfolder "Impersonation Test" in Inbox.
 
        Create the folder "Impersonation Test" in the test.mailbox Inbox folder.
 
    .EXAMPLE
        PS C:\> Test-ExchangeImpersonation -PrimarySMTPAddress test.mailbox@lab.local -Credential $cred -Action CreateDraft -Verbose -EWSUrl "https://mail.lab.local/ews/exchange.asmx"
        VERBOSE: Importing EWS library.
        VERBOSE: Using supplied credentials.
        VERBOSE: Connecting using EWS Url.
        VERBOSE: Creating message in drafts.
        Exception calling "Save" with "1" argument(s): "The request failed. The remote server returned an error: (401) Unauthorized."
        At C:\Users\administrator.LAB\Desktop\ModuleTesting\CPolydorou.Exchange\Exchange.psm1:986 char:29
        + $message.Save([Microsoft.Exchange.WebServices.Data.W ...
        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
            + FullyQualifiedErrorId : ServiceRequestException
 
        The user does not have permission to impersonate.
 
    #>


    [CmdletBinding()]
    Param
    (
        # The primary SMTP address of the target mailbox
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $PrimarySMTPAddress,

        # The credentials of the account with the impersonation rights
        [Parameter(Mandatory=$true,
                   Position=1)]
        $Credential,

        # The action to perform
        [Parameter(Mandatory=$true,
                   Position=2)]
        [ValidateSet('ListInboxItems','CreateSubfolder','CreateDraft','SendMessage')]
        $Action = "ListInboxItems",
        
        # The EWS URL
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
        [Alias('Url')]
        $EWSUrl,

        # The recipient of the test message (used with action "SendMessage")
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=4)]
        $Recipient
    )

    Begin
    {
        # Import the dll
        Write-Verbose "Importing EWS library."
        try
        {
            Add-Type -Path ($psscriptroot + "\Microsoft.Exchange.WebServices.dll")
        }
        catch
        {
            Throw "Could not load the EWS API."
            return
        }

        # Set Exchange Version
        $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013 

        # Create Exchange Service Object
        $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion) 

        # Configure the credentials
        if($Credential)
        {
            Write-Verbose "Using supplied credentials."
            $service.Credentials = New-Object System.Net.NetworkCredential($Credential.UserName.ToString(),$Credential.GetNetworkCredential().password.ToString())    
        }
        else
        {
            Write-Verbose "Using credentials from prompt."
            $c = Get-Credential
            $service.Credentials = New-Object System.Net.NetworkCredential($credential.UserName.ToString(),$c.GetNetworkCredential().password.ToString())    
        }
    }

    Process
    {
        # Set the EWS url
        try
        {
            if($EWSUrl)
            {
                Write-Verbose "Connecting using EWS Url."
                $service.Url = [system.URI] $EWSUrl
            }
            else
            {
                Write-Verbose "Connecting using autodiscover."
                $service.AutodiscoverUrl($PrimarySMTPAddress,{$true})
            }
        }
        catch
        {
            Throw $_
            return
        }
        # Set impersonation
        $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$PrimarySMTPAddress)

        switch ($Action)
        {
            'ListInboxItems' {
                                # Get messages in inbox
                                $properties = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::Id,
                                                                                                         [Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived,
                                                                                                         [Microsoft.Exchange.WebServices.Data.ItemSchema]::DisplayTo,
                                                                                                         [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)

                                $view = New-Object Microsoft.Exchange.WebServices.Data.ItemView(50)
                                $view.PropertySet = $properties

                                do
                                {    
                                    $findResults = $service.FindItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox, $view)
                                    foreach ($var in $findResults.Items)
                                    {
                                        [Microsoft.Exchange.WebServices.Data.EmailMessage]$var |
                                            Select-Object -Property Id,DateTimeCreated,DisplayTo,Subject
                                    }
                                    $view.Offset = 50;
                                }
                                while ($findResults.MoreAvailable)
                             }
            'CreateDraft' {
                            Write-Verbose "Creating message in drafts."
                            $message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
                            $message.Subject = "Test Impersonation"
                            $message.Body = "This is a test message created using impersonation."
                            $message.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Drafts)
                          }
            'CreateSubfolder' {
                                Write-Verbose 'Creating subfolder "Impersonation Test" in Inbox.'
                                # Create a folder in Inbox
                                $folder = New-Object Microsoft.Exchange.WebServices.Data.Folder($service)
                                $folder.DisplayName = "Impersonation Test";
                                $folder.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
                              }
            'SendMessage' {
                                # Send a message
                                if($Recipient -eq $null)
                                {
                                    Write-Error "Please specify a recipient."
                                    return
                                }

                                Write-Verbose "Sending a message to $Recipient."
                                $message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
                                $message.Subject = "Test Impersonation"
                                $message.Body = "This is a test message created using impersonation."
                                $message.ToRecipients.Add($Recipient);
                                $message.SendAndSaveCopy() |
                                    Out-Null
                              }
            Default {
                        Write-Verbose "No action specified"
                    }
        }
    }

    End
    {
    }
}
#endregion

#endregion

#region Exports
Export-ModuleMember -Function Get-PublicFolderReplicationStatus
Export-ModuleMember -Function Get-SendOnBehalfPermission
Export-ModuleMember -Function New-TerminationInboxRule
Export-ModuleMember -Function Test-DistributionGroupMember
Export-ModuleMember -Function Connect-Exchange
Export-ModuleMember -Function Move-ActiveMailboxDatabaseToPreference
Export-ModuleMember -Function Get-MailboxDatabaseCopyThatShouldBeActive
Export-ModuleMember -Function Rename-ExchangeShell
Export-ModuleMember -Function Get-SendConnectorDomains
Export-ModuleMember -Function Test-ExchangeImpersonation
#endregion