Functions/Sync-Entities.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<#
.SYNOPSIS
    This function performs a sync of two lists of entities.
.DESCRIPTION
    This function performs a sync of two lists of entities.
    This is a generic sync framework which can be used to sync most types of entities,
    depending on the script blocks which are provided.
#>

function Sync-Entities {
    [CmdletBinding(PositionalBinding=$false)]
    param (
        # The entities which are currently present.
        [Parameter(Mandatory=$true)]
        [AllowEmptyCollection()]
        [Object[]]$current,

        # The entities which are expected to be present.
        [Parameter(Mandatory=$true)]
        [AllowEmptyCollection()]
        [Object[]]$expected,

        # The type of entity that is to be synced.
        # This identity is used in information, warning and error messages.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$entityType,

        # The property of the entity to use as the key.
        # The value of this property must be not $null, and must be unique across all entities.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$entityKeyProperty,

        # The name of the entity property used as its identity.
        # This identity is used in information, warning and error messages, and can be
        # different from $entityKeyProperty.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$entityIdentityProperty,

        # Select the return type of this function.
        # This function can return the errors which occurred, which will be null if no errors occurred.
        # This function can also return the true/false result of whether the sync was successful.
        [Parameter(Mandatory=$false)]
        [ValidateSet("Errors", "Result")]
        [String]$returnType = "Result",

        # Select whether to create entities as part of the sync.
        [Parameter(Mandatory=$false)]
        [Boolean]$create = $false,

        # Select whether to update entities as part of the sync.
        [Parameter(Mandatory=$false)]
        [Boolean]$update = $false,

        # Select whether to delete/archive entities as part of the sync.
        [Parameter(Mandatory=$false)]
        [Boolean]$delete = $false,

        # Select whether the delete action deletes/archives entities.
        [Parameter(Mandatory=$false)]
        [ValidateSet("Archive", "Delete")]
        [String]$deleteAction = "Delete",

        # The script block used to un-archive an archived entity, if it exists.
        # Return values:
        # It should return "success" only if an archived entity was found as well as
        # successfully un-archived.
        # If no archived entity was found, return nothing.
        # Error handling:
        # This expression should throw an exception to indicate an error.
        [Parameter(Mandatory=$false)]
        [ValidateNotNull()]
        [ScriptBlock]$unArchiveEntity,

        # The script block used to create an entity.
        # Return values:
        # The script block should return "success" only if the entity was successfully created.
        # Error handling:
        # This expression should throw an exception to indicate an error.
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [ScriptBlock]$createEntity,

        # The script block used to compare two entities for equality.
        # Return values:
        # $true if the two entities are equal, $false or $null otherwise.
        # Error handling:
        # None required.
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [ScriptBlock]$compareEntities,

        # The expression used to update the properties of an entity.
        # Return values:
        # The script block should return "success" only if the entity was successfully updated.
        # Error handling:
        # This expression should throw an exception to indicate an error.
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [ScriptBlock]$updateEntity,

        # The script block used to archive an entity.
        # Return values:
        # The script block should return "success" only if the entity was successfully archived.
        # Error handling:
        # This expression should throw an exception to indicate an error.
        [Parameter(Mandatory=$false)]
        [ValidateNotNull()]
        [ScriptBlock]$archiveEntity,

        # The script block used to delete an entity.
        # Return values:
        # The script block should return "success" only if the entity was successfully deleted.
        # Error handling:
        # This expression should throw an exception to indicate an error.
        [Parameter(Mandatory=$false)]
        [ValidateNotNull()]
        [ScriptBlock]$deleteEntity,

        # A list containing the objects which will be passed to the script blocks
        # as input parameters.
        [Parameter(Mandatory=$false)]
        [ValidateScript({ $_.length -gt 0 })]
        [Object[]]$parameterObjects,

        # A list of the names for the objects which will be passed to the script blocks
        # as input parameters.
        # The order of this list needs to correspond to the order of $parameterObjects.
        # These names do not need to be the same as the names of the objects passed to
        # $parameterObjects, as these are the names used exclusively in the
        # script blocks to refer to those objects.
        [Parameter(Mandatory=$false)]
        [ValidateScript({ $_.length -gt 0 -and ($_ | Where-Object { $_.GetType() -eq [String] }) -eq $_ })]
        [Object[]]$parameterNames
    )

    # This function adds additional lines to the beginning of a script block
    # in order for it to be able to accept input parameters from this function.
    function Add-ScriptBlockInputParameters {
        param (
            # The script block to update.
            [Parameter(Mandatory=$true)]
            [ValidateNotNull()]
            [ScriptBlock]$scriptBlock
        )
        # Generate the code for the script block parameters
        $scriptBlockParametersCode = "param("

        # Add the parameters
        if ($parameterNames) {
            foreach ($parameter in $parameterNames) {
                $scriptBlockParametersCode += "`$$($parameter),"
            }
        }

        # Add the entity as the last parameter
        $scriptBlockParametersCode += "`$entity)"

        # Add to script block and return
        Write-Verbose "Adding parameters $($scriptBlockParametersCode) to the script block"
        [ScriptBlock]::Create($scriptBlockParametersCode + $scriptBlock.ToString())
    }

    # Create variable to store error messages
    $errorMessages = ""

    # Execute sync
    try {
        # Validate input parameters
        Write-Verbose "Validating `$parameterNames and `$parameterObjects."
        if ($parameterNames.length -ne $parameterObjects.length) {
            $errorMessages += "Length of `$parameterNames $($parameterNames.length) and `$parameterObjects $($parameterObjects.length) do not match."
            Write-Error $errorMessages
            throw $errorMessages
        }
        Write-Verbose "Validating parameter combinations for 'delete'."
        if ($delete) {
            if ($deleteAction -eq "Delete" -and [String]::IsNullOrWhiteSpace($deleteEntity)) {
                $errorMessages += "Delete is enabled and delete action is selected but expression to delete an entity has not been provided."
                Write-Error $errorMessages
                throw $errorMessages
            }
            elseif ($deleteAction -eq "Archive" -and [String]::IsNullOrWhiteSpace($archiveEntity)) {
                $errorMessages += "Delete is enabled and archive action is selected but expression to archive an entity has not been provided."
                Write-Error $errorMessages
                throw $errorMessages
            }
        }

        # Create hash table to help with syncing entities
        $entitiesHashTable = New-MergedObjectHashTable -CurrentObjects $current -ExpectedObjects $expected -KeyProperty $entityKeyProperty
        if ($null -eq $entitiesHashTable) {
            $errorMessages += "Failed to create merged hash table for syncing."
            Write-Error $errorMessages
            throw $errorMessages
        }

        # Run through hash table to sync entities
        $index = 0
        foreach ($entity in $entitiesHashTable.Values) {
            # Provide updates on progress
            $index += 1
            $syncProgress = "$($entityType) $($index)/$($entitiesHashTable.Count)"

            # Entity is to be created/un-archived
            if ($create -and !$entity.Current -and $entity.Expected) {
                # Retrieve the entity identity
                $entityIdentity = $entity.Expected.$entityIdentityProperty
                Write-Information "$($syncProgress): Creating/un-archiving $($entityType) '$($entityIdentity)'."

                # Un-archive entity if script block is provided
                if ($unArchiveEntity) {
                    # Try to un-archive entity
                    try {
                        $scriptBlock = Add-ScriptBlockInputParameters $unArchiveEntity
                        $argumentList = $parameterObjects + @($entity)
                        $unArchiveResult = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argumentList
                    }
                    catch {
                        $errorMessages += "$($syncProgress): Error while un-archiving $($entityType) '$($entityIdentity)'. `r`n$($_.Exception.Message)`r`n"
                        Write-Error $errorMessages
                        continue
                    }

                    # Un-archive was successful
                    if ($unArchiveResult -eq "success") {
                        Write-Verbose "$($syncProgress): Un-archived $($entityType) '$($entityIdentity)'."
                        continue
                    }
                }

                # Try to create entity
                try {
                    $scriptBlock = Add-ScriptBlockInputParameters $createEntity
                    $argumentList = $parameterObjects + @($entity)
                    $createResult = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argumentList
                }
                catch {
                    $errorMessages += "$($syncProgress): Error while creating $($entityType) '$($entityIdentity)'. `r`n$($_.Exception.Message)`r`n"
                    Write-Error $errorMessages
                    continue
                }

                # Create was successful
                if ($createResult -eq "success") {
                    Write-Verbose "$($syncProgress): Created $($entityType) '$($entityIdentity)'."
                }
                else {
                    Write-Error "$($syncProgress): Failed to create $($entityType) '$($entityIdentity)'."
                }
            }

            # Entity is to be updated
            elseif ($update -and $entity.Current -and $entity.Expected) {
                # Retrieve the entity identity
                $entityIdentity = $entity.Current.$entityIdentityProperty

                # Only update entity if it is different from the expected entity
                $scriptBlock = Add-ScriptBlockInputParameters $compareEntities
                $argumentList = $parameterObjects + @($entity)
                $comparisonResult = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argumentList
                if ($comparisonResult) {
                    Write-Information "$($syncProgress): $($entityType) '$($entityIdentity)' is up to date."
                    continue
                }

                # Continue with updating the entity
                Write-Information "$($syncProgress): Updating $($entityType) '$($entityIdentity)'."

                # Try to update the entity
                try {
                    $scriptBlock = Add-ScriptBlockInputParameters $updateEntity
                    $argumentList = $parameterObjects + @($entity)
                    $updateResult = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argumentList
                }
                catch {
                    $errorMessages += "$($syncProgress): Error while updating $($entityType) '$($entityIdentity)'. `r`n$($_.Exception.Message)`r`n"
                    Write-Error $errorMessages
                    continue
                }

                # Update was successful
                if ($updateResult -eq "success") {
                    Write-Verbose "$($syncProgress): Updated $($entityType) '$($entityIdentity)'."
                }
                else {
                    Write-Error "$($syncProgress): Failed to update $($entityType) '$($entityIdentity)'."
                }
            }

            # Entity is to be archived/deleted
            elseif ($delete -and $entity.Current -and !$entity.Expected) {
                # Retrieve the entity identity
                $entityIdentity = $entity.Current.$entityIdentityProperty

                # Archive only if action is selected and archive expression is provided
                if ($deleteAction -eq "Archive" -and $archiveEntity) {
                    Write-Information "$($syncProgress): Archiving $($entityType) '$($entityIdentity)'."

                    # Try to archive the entity
                    try {
                        $scriptBlock = Add-ScriptBlockInputParameters $archiveEntity
                        $argumentList = $parameterObjects + @($entity)
                        $archiveResult = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argumentList
                    }

                    # Error while archiving the entity
                    catch {
                        $errorMessages += "$($syncProgress): Error while archiving $($entityType) '$($entityIdentity)'. `r`n$($_.Exception.Message)`r`n"
                        Write-Error $errorMessages
                        continue
                    }

                    # Archive was successful
                    if ($archiveResult -eq "success") {
                        Write-Verbose "$($syncProgress): Archived $($entityType) '$($entityIdentity)'."
                    }
                    else {
                        Write-Error "$($syncProgress): Failed to archive $($entityType) '$($entityIdentity)'."
                    }
                }
                else {
                    Write-Information "$($syncProgress): Deleting $($entityType) '$($entityIdentity)'."

                    # Try to delete the entity
                    try {
                        $scriptBlock = Add-ScriptBlockInputParameters $deleteEntity
                        $argumentList = $parameterObjects + @($entity)
                        $deleteResult = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argumentList
                    }

                    # Error while deleting the entity
                    catch {
                        $errorMessages += "$($syncProgress): Error while deleting $($entityType) '$($entityIdentity)'. `r`n$($_.Exception.Message)`r`n"
                        Write-Error $errorMessages
                        continue
                    }

                    # Delete was successful
                    if ($deleteResult -eq "success") {
                        Write-Verbose "$($syncProgress): Deleted $($entityType) '$($entityIdentity)'."
                    }
                    else {
                        Write-Error "$($syncProgress): Failed to delete $($entityType) '$($entityIdentity)'."
                    }
                }
            }

            # No action is to be taken
            else {
                # Retrieve the entity identity
                if ($entity.Expected) {
                    $entityIdentity = $entity.Expected.$entityIdentityProperty
                }
                else {
                    $entityIdentity = $entity.Current.$entityIdentityProperty
                }

                # Output the information message
                Write-Information "$($syncProgress): No action to be taken for $($entityType) '$($entityIdentity)'."
            }
        }
    }
    catch {
        # An exception means that the sync failed
        $errorMessages = "An exception occurred during this function on line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)`r`n"
    }

    # Return the errors if there were any
    if (![String]::IsNullOrWhiteSpace($errorMessages)) {
        if ($returnType -eq "Errors") {
            return $errorMessages
        }
        # Return false to indicate unsuccessful sync
        else {
            return $false
        }
    }

    # Successful sync
    if ($returnType -eq "Result") {
        return $true
    }
}