tak.Connect-Exchange.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
function Connect-Exchange
{
    [CmdletBinding()]
    Param
    (
        # Specifies the ServerName that the session will be connected to
        [Parameter(Mandatory=$true,
                   ParameterSetName="Server",
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Server,

        # Credential used for connection; if not specified, the currently logged on user will be used
        [Parameter()]
        [pscredential]
        $Credential,

        # Specify the Online switch to connect to Exchange Online / Office 365
        [Parameter(ParameterSetName="Online")]
        [switch]
        $Online,
        
        # ProxyAccessType to use for the PsSession
        [Parameter()]
        [System.Management.Automation.Remoting.ProxyAccessType]
        $ProxyType = "None"
    )
    if ((Get-PSSession).ConfigurationName -ne "Microsoft.Exchange" -and $Credential) {
        $params = @{
            ConfigurationName = "Microsoft.Exchange";
            Name = "ExchMgmt";
            Authentication = "Kerberos";
            Credential = $Credential;
            ConnectionUri = "http://$Server/PowerShell/"
        }
    } elseif ((Get-PSSession).ConfigurationName -ne "Microsoft.Exchange" -and (-not $Credential)) {
        $params = @{
            ConfigurationName = "Microsoft.Exchange";
            Name = "ExOnPrem";
            Authentication = "Kerberos";
            ConnectionUri = "http://$Server/PowerShell/"
        }
    } else {
        Write-Warning "Already connected to Exchange"
        break
    }
    $ExchOption = New-PSSessionOption -ProxyAccessType $ProxyType
    try {
        if($online -and (Get-Command -Name New-ExoPSSession -ErrorAction SilentlyContinue)) {
            Write-Verbose "Connecting using Modern Auth"
            $sExch = New-ExoPSSession -PSSessionOption $ExchOption -ErrorAction Stop -ErrorVariable ExchangeSessionError
        } elseif ($Online) {
            if (-not($params.Credential)) {
                $params.Credential = Get-Credential
            }
            $params.ConnectionUri = "https://outlook.office365.com/powershell-liveid/"
            $params.Authentication = "Basic"
            $params.Name = "ExOnline"
            $params.Add("AllowRedirection",$true)
        } else {
            Write-Verbose "Trying to connect to $($params.ConnectionUri)"
            $sExch = New-PSSession @params -SessionOption $ExchOption -ErrorAction Stop -ErrorVariable ExchangeSessionError
        }
        Import-Module (Import-PSSession $sExch -AllowClobber) -Global -WarningAction SilentlyContinue
    } catch {
        Write-Warning "Could not connect to Exchange $($ExchangeSessionError.ErrorRecord)"
    }
}