Functions/Get-SyncMSPCompleteGroupsScriptBlocks.ps1

<#
.SYNOPSIS
    This function returns the script blocks used to sync MSPComplete groups.
#>

function Get-SyncMSPCompleteGroupsScriptBlocks {
    # Return the script blocks
    return @{
        CreateEntity = {
            # Set the local default parameter values
            # If this is not done, the local default parameter values are null
            $PSDefaultParameterValues = $Global:PSDefaultParameterValues

            # Create a hash table for the params
            $addBTCustomerGroupParams = @{
                Ticket      = $mspcObject.CustomerTicket
                Environment = $environment
            }

            # Add properties to the params
            foreach ($property in (Get-MSPCompleteGroupPropertyList)) {
                if (![String]::IsNullOrWhitespace($entity.Expected.$property)) {
                    $addBTCustomerGroupParams.Add($property, $entity.Expected.$property)
                }
            }

            # Create the group
            $newGroup = Add-BT_CustomerGroup @addBTCustomerGroupParams -Type CustomGroup -ErrorVariable errorVariable
            if (!$newGroup) {
                throw "Failed to create group.`r`n$($errorVariable)"
            }

            # Add the group extended properties
            $extendedPropertyErrors = ""
            foreach ($extendedProperty in (Get-MSPCompleteGroupExtendedPropertyList)) {
                if (![String]::IsNullOrWhitespace($entity.Expected.ExtendedProperties.$extendedProperty)) {
                    $extendedProperty = Add-BT_ExtendedProperty -Ticket $mspcObject.WorkgroupTicket `
                        -ReferenceEntityId $newGroup.Id -ReferenceEntityType "CustomerGroup" -Name $extendedProperty `
                        -Value $entity.Expected.ExtendedProperties.$extendedProperty -ErrorVariable errorVariable
                    if (!$extendedProperty) {
                        $extendedPropertyErrors += "Failed to create extended property '$($extendedProperty)': '$($entity.Expected.ExtendedProperties.$extendedProperty)'.`r`n$($errorVariable)"
                        continue
                    }
                }
            }
            if (![String]::IsNullOrWhitespace($extendedPropertyErrors)) {
                throw $extendedPropertyErrors
            }

            # Retrieve all MSPComplete end users
            $allEndUsers = Get-BT_CustomerEndUser -Ticket $mspcObject.CustomerTicket -RetrieveAll -IsArchived $false -IsDeleted $false

            # Add the group members
            $groupMemberErrors = ""
            foreach ($member in $entity.Expected.Members) {
                $endUser = $allEndUsers | Where-Object { $_.PrimaryEmailAddress -eq $member }
                if (!$endUser) {
                    $groupMemberErrors += "Cannot add the member '$($member)' to the group as it cannot be found."
                    continue
                }
                $groupMembership = Add-BT_GroupMembership -EndUserId $endUser.Id -GroupId $newGroup.Id -Ticket $mspcObject.CustomerTicket -ErrorVariable errorVariable
                if (!$groupMembership) {
                    $groupMemberErrors += "Failed to add member '$($member)' to the group.`r`n$($errorVariable)"
                    continue
                }
            }
            if (![String]::IsNullOrWhitespace($groupMemberErrors)) {
                throw $groupMemberErrors
            }

            # Successfully created the group
            "success"
        }
        CompareEntities = {
            # Set the local default parameter values
            # If this is not done, the local default parameter values are null
            $PSDefaultParameterValues = $Global:PSDefaultParameterValues

            # Error output is redirected to null to ensure that only the $true/$false result of the compare is returned
            Compare-MSPCompleteGroup -ReferenceGroup $entity.Expected -ComparisonGroup $entity.Current 2>$null
        }
        UpdateEntity = {
            # Set the local default parameter values
            # If this is not done, the local default parameter values are null
            $PSDefaultParameterValues = $Global:PSDefaultParameterValues

            # Create a hash table for params
            $setBTCustomerGroupParams = @{
                Ticket        = $mspcObject.CustomerTicket
                CustomerGroup = $entity.Current
                Environment   = $environment
            }

            # Add properties to the params
            foreach ($property in (Get-MSPCompleteGroupPropertyList)) {
                if (![String]::IsNullOrWhitespace($entity.Expected.$property) -and "$($entity.Expected.$property)" -ne "$($entity.Current.$property)") {
                    $setBTCustomerGroupParams.Add($property, $entity.Expected.$property)
                }
            }

            # Update the group
            if ($setBTCustomerGroupParams.Count -gt 3) {
                $updatedGroup = Set-BT_CustomerGroup @setBTCustomerGroupParams -ErrorVariable errorVariable
                if (!$updatedGroup) {
                    throw "Failed to update group properties.`r`n$($errorVariable)"
                }
            }

            # Create the missing extended properties
            $extendedPropertyErrors = ""
            $missingExtendedProperties = Get-MSPCompleteGroupExtendedPropertyList | Where-Object {
                ![String]::IsNullOrWhitespace($entity.Expected.ExtendedProperties.$_) -and
                !$entity.Current.ExtendedProperties.ContainsKey($_)
            }
            if ($missingExtendedProperties.Length -gt 0) {
                foreach ($extendedproperty in $missingExtendedProperties) {
                    $extendedProperty = Add-BT_ExtendedProperty -Ticket $mspcObject.WorkgroupTicket `
                        -ReferenceEntityId $entity.Current.Id -ReferenceEntityType "CustomerGroup" -Name $extendedProperty `
                        -Value $entity.Expected.ExtendedProperties.$extendedProperty -ErrorVariable errorVariable
                    if (!$extendedProperty) {
                        $extendedPropertyErrors += "Failed to create extended property '$($extendedProperty)': '$($entity.Expected.ExtendedProperties.$extendedProperty)'.`r`n$($errorVariable)"
                        continue
                    }
                }
            }

            # Delete the additional extended properties
            $additionalExtendedProperties = Get-MSPCompleteGroupExtendedPropertyList | Where-Object {
                ![String]::IsNullOrWhitespace($entity.Current.ExtendedProperties.$_) -and
                !$entity.Expected.ExtendedProperties.ContainsKey($_)
            }
            if ($additionalExtendedProperties.Length -gt 0) {
                foreach ($extendedproperty in $additionalExtendedProperties) {
                    $extendedProperty = Get-BT_ExtendedProperty -Ticket $mspcObject.WorkgroupTicket -ReferenceEntityId $entity.Current.Id -Name $extendedProperty -IsDeleted $false
                    if (!$extendedProperty) {
                        $extendedPropertyErrors += "Failed to delete extended property '$($extendedProperty)' as it cannot be found."
                        continue
                    }
                    Remove-BT_ExtendedProperty -Ticket $mspcObject.WorkgroupTicket -Id $extendedProperty.Id -Force
                }
            }

            # Update the different extended properties
            $differentExtendedProperties = Get-MSPCompleteGroupExtendedPropertyList | Where-Object {
                ![String]::IsNullOrWhitespace($entity.Expected.ExtendedProperties.$_) -and
                $entity.Current.ExtendedProperties.ContainsKey($_) -and
                $entity.Expected.ExtendedProperties.ContainsKey($_)
            }
            if ($differentExtendedProperties.Length -gt 0) {
                foreach ($extendedproperty in $differentExtendedProperties) {
                    $extendedPropertyObject = Get-BT_ExtendedProperty -Ticket $mspcObject.WorkgroupTicket -ReferenceEntityId $entity.Current.Id -Name $extendedProperty -IsDeleted $false
                    if (!$extendedPropertyObject) {
                        $extendedPropertyErrors += "Failed to update extended property '$($extendedProperty)' as it cannot be found."
                        continue
                    }
                    $updatedExtendedProperty = Set-BT_ExtendedProperty -Ticket $mspc.WorkgroupTicket -ExtendedProperty $extendedPropertyObject -Value $entity.Expected.ExtendedProperties.$extendedProperty -ErrorVariable errorVariable
                    if (!$updatedExtendedProperty) {
                        $extendedPropertyErrors += "Failed to update extended property '$($extendedProperty)'.`r`n$($errorVariable)"
                        continue
                    }
                }
            }
            if (![String]::IsNullOrWhitespace($extendedPropertyErrors)) {
                throw $extendedPropertyErrors
            }

            # Retrieve all MSPComplete end users
            $allEndUsers = Get-BT_CustomerEndUser -Ticket $mspcObject.CustomerTicket -RetrieveAll -IsArchived $false -IsDeleted $false

            # Add the missing group members
            $groupMemberErrors = ""
            $missingGroupMembers = $entity.Expected.Members | Where-Object { $_ -notIn $entity.Current.Members }
            foreach ($member in $missingGroupMembers) {
                $endUser = $allEndUsers | Where-Object { $_.PrimaryEmailAddress -eq $member }
                if (!$endUser) {
                    $groupMemberErrors += "Cannot add the member '$($member)' to the group as it cannot be found."
                    continue
                }
                $groupMembership = Add-BT_GroupMembership -EndUserId $endUser.Id -GroupId $entity.Current.Id -Ticket $mspcObject.CustomerTicket -ErrorVariable errorVariable
                if (!$groupMembership) {
                    $groupMemberErrors += "Failed to add member '$($member)' to the group.`r`n$($errorVariable)"
                    continue
                }
            }

            # Remove the additional group members
            $additionalGroupMembers = $entity.Current.Members | Where-Object { $_ -notIn $entity.Expected.Members }
            foreach ($member in $additionalGroupMembers) {
                $endUser = $allEndUsers | Where-Object { $_.PrimaryEmailAddress -eq $member }
                if (!$endUser) {
                    $groupMemberErrors += "Cannot remove the member '$($member)' from the group as it cannot be found."
                    continue
                }
                $groupMembership = Get-BT_GroupMembership -Ticket $mspcObject.CustomerTicket -GroupId $entity.Current.Id -EndUserId $endUser.Id -IsDeleted $false
                if (!$groupMembership) {
                    $groupMemberErrors += "Cannot remove the member '$($member)' from the group as the group membership object cannot be found."
                    continue
                }
                Remove-BT_GroupMembership -Ticket $mspc.CustomerTicket -Id $groupMembership.Id -Force
            }
            if (![String]::IsNullOrWhitespace($groupMemberErrors)) {
                throw $groupMemberErrors
            }
        }
        DeleteEntity = {
            # Set the local default parameter values
            # If this is not done, the local default parameter values are null
            $PSDefaultParameterValues = $Global:PSDefaultParameterValues

            # Remove the group
            Remove-BT_CustomerGroup -Ticket $mspcObject.CustomerTicket -Id $entity.Current.Id -Force
            "success"
        }
    }
}