-
Notifications
You must be signed in to change notification settings - Fork 0
/
revoke.groups.ps1
282 lines (258 loc) · 14.7 KB
/
revoke.groups.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#region Initialize default properties
$c = $configuration | ConvertFrom-Json
$p = $person | ConvertFrom-Json;
$m = $manager | ConvertFrom-Json;
$aRef = $accountReference | ConvertFrom-Json;
$mRef = $managerAccountReference | ConvertFrom-Json;
# The permissionReference object contains the Identification object provided in the retrieve permissions call
$pRef = $permissionReference | ConvertFrom-Json;
$success = $True
$auditLogs = [Collections.Generic.List[PSCustomObject]]::new()
# Set TLS to accept TLS, TLS 1.1 and TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
$VerbosePreference = "SilentlyContinue"
$InformationPreference = "Continue"
$WarningPreference = "Continue"
# Used to connect to Exchange using user credentials (MFA not supported).
$ConnectionUri = $c.ConnectionUri
$Username = $c.Username
$Password = $c.Password
$AuthenticationMethod = $c.AuthenticationMethod
# Troubleshooting
# $aRef = @{
# Guid = "ae71715a-2964-4ce6-844a-b684d61aa1e5"
# UserPrincipalName = "[email protected]"
# }
# $dryRun = $false
#region functions
# Write functions logic here
function Set-PSSession {
<#
.SYNOPSIS
Get or create a "remote" Powershell session
.DESCRIPTION
Get or create a "remote" Powershell session at the local computer
.EXAMPLE
PS C:\> $remoteSession = Set-PSSession -PSSessionName ($psSessionName + $mutex.Number) # Test1
Get or Create a "remote" Powershell session at the local computer with computername and number: Test1 And assign to a $varaible which can be used to make remote calls.
.OUTPUTS
$remoteSession [System.Management.Automation.Runspaces.PSSession]
.NOTES
Make sure you always disconnect the PSSession, otherwise the PSSession is blocked to reconnect.
Place the following code in the finally block to make sure the session will be disconnected
if ($null -ne $remoteSession) {
Disconnect-PSSession $remoteSession
}
#>
[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 "Remote Powershell session is found, Name: $($sessionObject.Name), ComputerName: $($sessionObject.ComputerName)"
} catch {
Write-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 "Remote Powershell session is created, Name: $($sessionObject.Name), ComputerName: $($sessionObject.ComputerName)"
} catch {
throw "Couldn't created a PowerShell Session: $($_.Exception.Message)"
}
}
Write-Verbose "Remote Powershell Session '$($sessionObject.Name)' State: '$($sessionObject.State)' Availability: '$($sessionObject.Availability)'"
if ($sessionObject.Availability -eq "Busy") {
throw "Remote session is in Use"
}
Write-Output $sessionObject
}
#endregion functions
try {
if($dryRun -eq $false){
$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 }
# revoke Exchange Online Groupmembership
$removeExchangeGroupMembership = Invoke-Command -Session $remoteSession -ScriptBlock {
try{
$aRef = $using:aRef
$pRef = $using:pRef
$success = $false
$auditLogs = [Collections.Generic.List[PSCustomObject]]::new()
# 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()
[Void]$verboseLogs.Add("revoking permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))")
$removeDGMember = Remove-DistributionGroupMember -Identity $pRef.id -Member $aRef.Guid -BypassSecurityGroupManagerCheck:$true -Confirm:$false -ErrorAction Stop
[Void]$informationLogs.Add("Successfully revoked Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))")
$success = $true
$auditLogs.Add([PSCustomObject]@{
Action = "RevokePermission"
Message = "Successfully revoked Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))"
IsError = $false
}
)
} catch {
if($_ -like "*isn't a member of the group*"){
[Void]$warningLogs.Add("The recipient $($aRef.UserPrincipalName) ($($aRef.Guid)) is not a member of the group $($pRef.Name) ($($pRef.id))")
$success = $true
$auditLogs.Add([PSCustomObject]@{
Action = "RevokePermission"
Message = "Successfully revoked Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))"
IsError = $false
}
)
}elseif($_ -like "*object '$($pRef.id)' couldn't be found*"){
[Void]$warningLogs.Add("Group $($pRef.Name) ($($pRef.id)) couldn't be found. Possibly no longer exists. Skipping action")
$success = $true
$auditLogs.Add([PSCustomObject]@{
Action = "RevokePermission"
Message = "Successfully revoked Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))"
IsError = $false
}
)
}elseif($_ -like "*Couldn't find object ""$($aRef.Guid)""*"){
[Void]$warningLogs.Add("User $($aRef.UserPrincipalName) ($($aRef.Guid)) couldn't be found. Possibly no longer exists. Skipping action")
$success = $true
$auditLogs.Add([PSCustomObject]@{
Action = "RevokePermission"
Message = "Successfully revoked Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))"
IsError = $false
}
)
}else{
# Log error for further analysis. Contact Tools4ever Support to further troubleshoot
[Void]$warningLogs.Add("Error revoking Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid)). Error: $_")
$success = $false
$auditLogs.Add([PSCustomObject]@{
Action = "RevokePermission"
Message = "Failed to revoke Permission $($pRef.Name) ($($pRef.id)) from $($aRef.UserPrincipalName) ($($aRef.Guid))"
IsError = $true
}
)
}
} finally {
$returnobject = @{
success = $success
auditLogs = $auditLogs
verboseLogs = $verboseLogs
informationLogs = $informationLogs
warningLogs = $warningLogs
errorLogs = $errorLogs
}
Remove-Variable ("aRef","pRef","success","auditLogs","verboseLogs","informationLogs","warningLogs","errorLogs")
Write-Output $returnobject
}
}
}
$success = $removeExchangeGroupMembership.success
$auditLogs = $removeExchangeGroupMembership.auditLogs
# Log the data from logging arrarys (since the "normal" Write-Information isn't sent to HelloID as another PS session performs the commands)
$verboseLogs = $removeExchangeGroupMembership.verboseLogs
foreach($verboseLog in $verboseLogs){ Write-Verbose $verboseLog }
$informationLogs = $removeExchangeGroupMembership.informationLogs
foreach($informationLog in $informationLogs){ Write-Information $informationLog }
$warningLogs = $removeExchangeGroupMembership.warningLogs
foreach($warningLog in $warningLogs){ Write-Warning $warningLog }
$errorLogs = $removeExchangeGroupMembership.errorLogs
foreach($errorLog in $errorLogs){ Write-Warning $errorLog }
}
catch {
$auditLogs.Add([PSCustomObject]@{
Action = "RevokePermission"
Message = "Failed to revoke permission: $_"
IsError = $True
});
$success = $false
Write-Warning $_;
} 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)'"
}
}
#build up result
$result = [PSCustomObject]@{
Success = $success
AuditLogs = $auditLogs
# Account = [PSCustomObject]@{ }
};
Write-Output $result | ConvertTo-Json -Depth 10;