Connect-EWSService.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
function Connect-EWSService {
    [OutputType('Microsoft.Exchange.WebServices.Data.ExchangeService')]
    [CmdletBinding()]
    param (
        [Parameter(
                Mandatory
        )]
        [String]$Mailbox,

        [String]$ServiceUrl,

        [Microsoft.Exchange.WebServices.Data.ExchangeVersion]
        $Version = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1,
        
        [switch]$AllowRedirect,
        
        [Management.Automation.PSCredential]
        [Management.Automation.Credential()]
        $Credential = [Management.Automation.PSCredential]::Empty
    )

    $exchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService $Version

    if ($Credential -ne [Management.Automation.PSCredential]::Empty) {
        $exchangeService.UseDefaultCredentials = $false
        $exchangeService.Credentials = $Credential.GetNetworkCredential()   
    } else {
        $exchangeService.UseDefaultCredentials = $true
    }

    if ($ServiceUrl) {
        $exchangeService.Url = $ServiceUrl
    } else {
        try {
            $exchangeService.AutodiscoverUrl($Mailbox,{[bool]$AllowRedirect})
        } catch {
            throw "Failed to identify Url for $Mailbox - $_"
        }
    }

    $Script:exchangeService = $exchangeService
    $Script:connections.Add(
        $exchangeService,
        $Mailbox
    )
    $exchangeService
}