-
Notifications
You must be signed in to change notification settings - Fork 0
/
enable.ps1
239 lines (218 loc) · 11.5 KB
/
enable.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
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
#################################################
# HelloID-Conn-Prov-Target-Exchange-On-Premise-Enable
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
# Set debug logging
switch ($($actionContext.Configuration.config.isDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
#Exchange configuration
$ConnectionUri = $actionContext.Configuration.exchange.ConnectionUri
$Username = $actionContext.Configuration.exchange.username
$Password = $actionContext.Configuration.exchange.password
$AuthenticationMethod = $actionContext.Configuration.exchange.authenticationmode
#region functions
function Set-PSSession {
[OutputType([System.Management.Automation.Runspaces.PSSession])]
param(
[Parameter(mandatory)]
[string]$PSSessionName
)
try {
$sessionObject = Get-PSSession -ComputerName $env:computername -Name $PSSessionName -ErrorAction stop
if ($null -eq $sessionObject) {
# Due to some inconsistency, the Get-PSSession does not always throw an error
throw "The command cannot find a PSSession that has the name '$PSSessionName'."
}
# To Avoid using mutliple sessions at the same time.
if ($sessionObject.length -gt 1) {
Remove-PSSession -Id ($sessionObject.id | Sort-Object | select-object -first 1)
$sessionObject = Get-PSSession -ComputerName $env:computername -Name $PSSessionName -ErrorAction stop
}
Write-Verbose -Verbose "Remote Powershell session is found, Name: $($sessionObject.Name), ComputerName: $($sessionObject.ComputerName)"
}
catch {
Write-Verbose -Verbose "Remote Powershell session not found: $($_)"
}
if ($null -eq $sessionObject) {
try {
$remotePSSessionOption = New-PSSessionOption -IdleTimeout (New-TimeSpan -Minutes 5).TotalMilliseconds
$sessionObject = New-PSSession -ComputerName $env:computername -EnableNetworkAccess:$true -Name $PSSessionName -SessionOption $remotePSSessionOption
Write-Verbose -Verbose "Remote Powershell session is created, Name: $($sessionObject.Name), ComputerName: $($sessionObject.ComputerName)"
}
catch {
throw "Couldn't created a PowerShell Session: $($_.Exception.Message)"
}
}
if ($sessionObject.Availability -eq "Busy") {
throw "Remote session is in Use"
}
Write-Output $sessionObject
}
#endregion
try {
# Verify if [aRef] has a value
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
throw 'The account reference could not be found'
}
Write-Information 'Verifying if a Exchange-On-Premise account exists'
$remoteSession = Set-PSSession -PSSessionName 'HelloID_Prov_Exchange'
Connect-PSSession $remoteSession | out-null
# if it does not exist create new session to exchange in remote session
$createSessionResult = Invoke-Command -Session $remoteSession -ScriptBlock {
# Create array for logging since the "normal" Write-Information isn't sent to HelloID as another PS session performs the commands
$verboseLogs = [System.Collections.ArrayList]::new()
$informationLogs = [System.Collections.ArrayList]::new()
$warningLogs = [System.Collections.ArrayList]::new()
$errorLogs = [System.Collections.ArrayList]::new()
# Check if Exchange Connection already exists
try {
$checkCmd = Get-User -ResultSize 1 -ErrorAction Stop | Out-Null
$connectedToExchange = $true
}
catch {
if ($_.Exception.Message -like "The term 'Get-User' is not recognized as the name of a cmdlet, function, script file, or operable program.*") {
$connectedToExchange = $false
}
}
# Connect to Exchange
try {
if ($connectedToExchange -eq $false) {
$connectionUri = $using:ConnectionUri
$authenticationMethod = $using:AuthenticationMethod
$password = $using:Password
$username = $using:Username
[Void]$verboseLogs.Add("Connecting to Exchange: $connectionUri..")
# Connect to Exchange in an unattended scripting scenario using user credentials (MFA not supported).
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = [System.Management.Automation.PSCredential]::new($username, $securePassword)
$sessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -IdleTimeout (New-TimeSpan -Minutes 5).TotalMilliseconds # The session does not time out while the session is active. Please enter this value to time out the Exchangesession when the session is removed
$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionUri -Credential $credential -Authentication $authenticationMethod -AllowRedirection -SessionOption $sessionOption -EnableNetworkAccess:$false -ErrorAction Stop
$null = Import-PSSession $exchangeSession
[Void]$informationLogs.Add("Successfully connected to Exchange: $connectionUri")
}
else {
[Void]$verboseLogs.Add("Already connected to Exchange")
}
}
catch {
if (-Not [string]::IsNullOrEmpty($_.Exception.InnerExceptions)) {
$errorMessage = "$($_.Exception.InnerExceptions)"
}
else {
$errorMessage = "$($_.Exception.Message) $($_.ScriptStackTrace)"
}
[Void]$warningLogs.Add($errorMessage)
throw "Could not connect to Exchange, error: $_"
}
finally {
$returnobject = @{
verboseLogs = $verboseLogs
informationLogs = $informationLogs
warningLogs = $warningLogs
errorLogs = $errorLogs
}
Remove-Variable ("verboseLogs", "informationLogs", "warningLogs", "errorLogs")
Write-Output $returnobject
}
}
# Log the data from logging arrarys (since the "normal" Write-Information isn't sent to HelloID as another PS session performs the commands)
$verboseLogs = $createSessionResult.verboseLogs
foreach ($verboseLog in $verboseLogs) { Write-Verbose $verboseLog }
$informationLogs = $createSessionResult.informationLogs
foreach ($informationLog in $informationLogs) { Write-Information $informationLog }
$warningLogs = $createSessionResult.warningLogs
foreach ($warningLog in $warningLogs) { Write-Warning $warningLog }
$errorLogs = $createSessionResult.errorLogs
foreach ($errorLog in $errorLogs) { Write-Warning $errorLog }
try {
$getExchangeUser = Invoke-Command -Session $remoteSession -ScriptBlock {
$aref = $using:actionContext.References.Account
$correlatedMailbox = Get-Mailbox -Identity $aref
Write-Output $correlatedMailbox
} -ErrorAction Stop
if ($getExchangeUser.Name.Count -eq 0) {
Write-Information "Could not find mailbox with identity [$($actionContext.References.Account)] [$($actionContext.Data.userPrincipalName)]"
$action = 'NotFound'
}
if ($getExchangeUser.Name.Count -gt 0) {
Write-Information "Correlation found mailbox for: [$($actionContext.References.Account)] [$($actionContext.Data.userPrincipalName)]"
$action = 'EnableAccount'
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "$action mailbox for: [$($actionContext.References.Account)] [$($actionContext.Data.userPrincipalName)] will be executed."
IsError = $false
})
}
}
catch {
if ($_.Exception.ErrorRecord.CategoryInfo.Reason -eq "ManagementObjectNotFoundException") {
Write-Warning "Could not find mailbox with identity [$($actionContext.References.Account)] [$($actionContext.Data.userPrincipalName)]"
$action = 'NotFound'
}
else {
if (-Not [string]::IsNullOrEmpty($_.Exception.InnerExceptions)) {
$errorMessage = "$($_.Exception.InnerExceptions)"
}
else {
$errorMessage = "$($_.Exception.Message) $($_.ScriptStackTrace)"
}
Write-Warning $errorMessage
throw "Regular Error, error: $_"
}
}
# Process
switch ($action) {
'EnableAccount' {
if (-not($actionContext.DryRun -eq $true)) {
Write-Information "Enabling Exchange-On-Premise account with accountReference: [$($actionContext.References.Account)]"
try {
Invoke-Command -Session $remoteSession -ScriptBlock {
$aref = $using:actionContext.References.Account
Set-Mailbox -Identity $aref -HiddenFromAddressListsEnabled $False
} -ErrorAction Stop
}
catch {
throw $_
}
}
else {
Write-Information "[DryRun] Enable Exchange-On-Premise account with accountReference: [$($actionContext.References.Account)], will be executed during enforcement"
}
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = 'Enable mailbox was successful'
IsError = $false
})
break
}
'NotFound' {
Write-Information "Exchange-On-Premise account: [$($actionContext.References.Account)] could not be found, possibly indicating that it could be deleted"
$outputContext.Success = $false
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Exchange-On-Premise account: [$($actionContext.References.Account)] could not be found, possibly indicating that it could be deleted"
IsError = $true
})
break
}
}
}
catch {
$outputContext.success = $false
$ex = $PSItem
$auditMessage = "Error $($actionMessage). Error: $($ex.Exception.Message)"
Write-Warning "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = $auditMessage
IsError = $true
})
}
finally {
Start-Sleep 1
if ($null -ne $remoteSession) {
Disconnect-PSSession $remoteSession -WarningAction SilentlyContinue | out-null # Suppress Warning: PSSession Connection was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. # to fix the warning the session must be created with a elevated prompt
Write-Verbose "Remote Powershell Session '$($remoteSession.Name)' State: '$($remoteSession.State)' Availability: '$($remoteSession.Availability)'"
}
}