Private/ConnectionReferences.ps1

function Invoke-SetConnectionReferences {
    Param(
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient] $CRMConn,
        [string] [Parameter(Mandatory = $true)] $SolutionName,
        [string] [Parameter(Mandatory = $true)] $EnvId,
        [bool] [Parameter(Mandatory = $false)] $RunLocally = $false
    )
    
    Write-Host "Checking for Connections References in $SolutionName"
    $solutions = Get-CrmRecords -conn $CRMConn -EntityLogicalName "solution" -FilterAttribute "uniquename" -FilterOperator "eq" -FilterValue $SolutionName
    $solutionId = $solutions.CrmRecords[0].solutionid
    $connRefs = (Get-CrmRecords -conn $CRMConn -EntityLogicalName "connectionreference" -FilterAttribute "solutionid" -FilterOperator "eq" -FilterValue $solutionid -Fields connectionreferencelogicalname, connectionid, connectorid, connectionreferenceid).CrmRecords
    foreach ($connReference in $connRefs) {
        try {
            $connectionType = $connReference.connectorid.Replace("/providers/Microsoft.PowerApps/apis/", "")
            Write-PPDOMessage -Message "Found Connection Reference $($connReference.connectionreferencelogicalname), searching for related Connection" -RunLocally $RunLocally

            $connection = Get-AdminPowerAppConnection -EnvironmentName $EnvId | Select-Object -ExpandProperty Statuses -Property ConnectionName, DisplayName, ConnectorName, CreatedBy, CreatedTime | Where-Object { ($_.status -eq "Connected") -and ($_.ConnectorName -eq $connectionType) } | Sort-Object -Property CreatedTime

            if (!$connection) {
                Throw "Unable to find a Connection in this environment of type $connectionType."
            }

            # Get Dataverse systemuserid for the system user that maps to the aad user guid that created the connection
            $systemusers = Get-CrmRecords -conn $CRMConn -EntityLogicalName "systemuser" -FilterAttribute "azureactivedirectoryobjectid" -FilterOperator "eq" -FilterValue $connection[0].CreatedBy.id -Fields "domainname"

            if (!($systemusers.Count -gt 0)) {
                Throw "Unable to find a systemuser in CRM for the user $($connection[0].CreatedBy.displayName) ($($connection[0].CreatedBy.userPrincipalName)), so unable to impersonate them to set Connection Reference $($connReference.connectionreferencelogicalname)."
            }

            Write-Host "Impersonating the creator of the Connection - $($systemusers.CrmRecords[0].domainname)"
            # Impersonate the Dataverse systemuser that created the connection when updating the connection reference
            $impersonationCallerId = $systemusers.CrmRecords[0].systemuserid
            $impersonationConn = $CRMConn
            $impersonationConn.OrganizationWebProxyClient.CallerId = $impersonationCallerId 
            Write-PPDOMessage -Message "Setting Connection Reference to use $($connection[0].DisplayName)" -Type "command" -RunLocally $RunLocally
            Set-CrmRecord -conn $impersonationConn -EntityLogicalName $connReference.logicalname -Id $connReference.connectionreferenceid -Fields @{"connectionid" = $connection[0].ConnectionName }
        }
        catch {
            Write-PPDOMessage -Message "An error occurred for Connection Reference $($connReference.connectionreferencelogicalname). Some of your Flows may not Activate successfully." -type "warning" -LogWarning $true -RunLocally $RunLocally
            Write-PPDOMessage -Message "Error Message: $_"
        }
    }
}