Exchange.psm1

#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