-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnect-TkMsService.ps1
More file actions
170 lines (166 loc) · 7.79 KB
/
Connect-TkMsService.ps1
File metadata and controls
170 lines (166 loc) · 7.79 KB
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
<#
.SYNOPSIS
Connects to Microsoft Graph and/or Exchange Online services.
.DESCRIPTION
The Connect-TkMsService function establishes a connection to Microsoft Graph and/or Exchange Online services.
It checks for existing sessions and reuses them if valid, otherwise, it creates new sessions.
The function supports logging and provides detailed information about the connection process.
.PARAMETER MgGraph
Switch parameter to indicate if a connection to Microsoft Graph should be established.
.PARAMETER GraphAuthScopes
Array of strings specifying the scopes required for Microsoft Graph authentication.
.PARAMETER ExchangeOnline
Switch parameter to indicate if a connection to Exchange Online should be established.
.EXAMPLE
Connect-TkMsService -MgGraph -GraphAuthScopes @('User.Read', 'Mail.Read')
This example connects to Microsoft Graph with the specified scopes.
.EXAMPLE
Connect-TkMsService -ExchangeOnline
This example connects to Exchange Online.
.EXAMPLE
Connect-TkMsService -MgGraph -GraphAuthScopes @('User.Read', 'Mail.Read') -ExchangeOnline
This example connects to both Microsoft Graph and Exchange Online.
.NOTES
This function requires the Microsoft.Graph and ExchangeOnlineManagement modules to be installed and imported.
#>
function Connect-TkMsService {
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param (
[Parameter(
HelpMessage = 'Switch to connect to Microsoft Graph.'
)]
[Switch]
$MgGraph,
[Parameter(
HelpMessage = 'Array of scopes required for Microsoft Graph authentication.'
)]
[String[]]
$GraphAuthScopes,
[Parameter(
HelpMessage = 'Switch to connect to Exchange Online.'
)]
[Switch]
$ExchangeOnline
)
# Used Cmdlets
# Get-MgUser, Get-MgContext, Get-MgOrganization, Remove-MgContext, Connect-MgGraph, Disconnect-ExchangeOnline, Connect-ExchangeOnline
# Begin Logging
if (-not $script:LogString) {
Write-AuditLog -Start
}
else {
Write-AuditLog -BeginFunction
}
Write-AuditLog '###############################################'
#----------------------------------------------
# Section 1: Microsoft Graph
#----------------------------------------------
if ($MgGraph) {
$shouldProcessTarget = $GraphAuthScopes -join ', '
$shouldProcessOperation = 'Connect-MgGraph'
if ($PSCmdlet.ShouldProcess($shouldProcessTarget, $shouldProcessOperation)) {
try {
# 1) Attempt to see if we have a valid Graph session
$graphIsValid = $false
try {
# If this succeeds, presumably we have a valid token/context
Get-MgUser -Top 1 -ErrorAction Stop | Out-Null
$ContextMg = Get-MgContext -ErrorAction Stop
# Check required scopes
$scopesNeeded = $GraphAuthScopes
$missing = $scopesNeeded | Where-Object { $ContextMg.Scopes -notcontains $_ }
if ($missing) {
Write-AuditLog "The following needed scopes are missing: $($missing -join ', ')"
}
else {
Write-AuditLog 'An active Microsoft Graph session is detected and all required scopes are present.'
$graphIsValid = $true
}
}
catch {
# Either no session or it's invalid/expired
$graphIsValid = $false
}
# 2) If valid session, ask user if they want to reuse it
if ($graphIsValid) {
$org = Get-MgOrganization -ErrorAction Stop
$shouldProcessTarget = 'Microsoft Graph'
$shouldProcessOperation = "Use existing session for Account: $($ContextMg.Account) Tenant: $($org.DisplayName) AuthType: $($ContextMg.AuthType)"
if ($PSCmdlet.ShouldProcess($shouldProcessTarget, $shouldProcessOperation)) {
Write-AuditLog 'Using existing Microsoft Graph session.'
}
else {
# Remove the old context so we can connect fresh
Remove-MgContext -ErrorAction SilentlyContinue
Write-AuditLog 'Creating a new Microsoft Graph session.'
Connect-MgGraph -ContextScope Process -Scopes $scopesNeeded `
-ErrorAction Stop | Out-Null
Write-AuditLog 'Connected to Microsoft Graph.'
}
}
else {
# No valid session, so just connect
Write-AuditLog 'No valid Microsoft Graph session found. Connecting...'
Connect-MgGraph -ContextScope Process -Scopes $scopesNeeded `
-ErrorAction Stop | Out-Null
Write-AuditLog 'Connected to Microsoft Graph.'
}
}
catch {
Write-AuditLog -Severity Error -Message "Error connecting to Microsoft Graph. Error: $($_.Exception.Message)"
throw
}
}
}
#----------------------------------------------
# Section 2: Exchange Online
#----------------------------------------------
if ($ExchangeOnline) {
$shouldProcessTarget = 'Connecting to Exchange Online using modern authentication pop-up.'
$shouldProcessOperation = 'Connect-ExchangeOnline'
if ($PSCmdlet.ShouldProcess($shouldProcessTarget, $shouldProcessOperation)) {
try {
# 1) Attempt to see if we have a valid Exchange session
$exoIsValid = $false
try {
$ExoOrg = Get-OrganizationConfig -ErrorAction Stop
$exoIsValid = $true
}
catch {
# Either no session or it's invalid/expired
$exoIsValid = $false
}
# 2) If valid session, ask user if they want to reuse it
if ($exoIsValid) {
Write-AuditLog 'An active Exchange Online session is detected.'
Write-AuditLog "Tenant: `n$($ExoOrg.DisplayName)`n"
$shouldProcessTarget = 'ExchangeOnline'
$shouldProcessOperation = "Use existing session for Org: $($ExoOrg.DisplayName) OnMicrosoftId: $($ExoOrg.Name )"
if ($PSCmdlet.ShouldProcess($shouldProcessTarget, $shouldProcessOperation)) {
Write-AuditLog 'Using existing Exchange Online session.'
}
else {
# Disconnect old session
Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
Write-AuditLog 'Creating new Exchange Online session.'
Connect-ExchangeOnline -ShowBanner:$false -ErrorAction Stop
Write-AuditLog 'Connected to Exchange Online.'
}
}
else {
Write-AuditLog 'No valid Exchange Online session found. Connecting...'
Connect-ExchangeOnline -ShowBanner:$false -ErrorAction Stop
Write-AuditLog 'Connected to Exchange Online.'
}
}
catch {
Write-AuditLog -Severity Error -Message "Error connecting to Exchange Online. Error: $($_.Exception.Message)"
throw
}
}
}
else {
Write-AuditLog 'No service specified for connection.'
}
Write-AuditLog -EndFunction
}