Search code examples
dynamics-crmdynamics-crm-online

how to Publish duplicate detection rule?


We have duplicate detection rule which will go inactive status once we import it in other env. how to enable the rule using PowerShell using web API.


Solution

  • You can publish(enable) the rule by calling the webapi action PublishDuplicateRule.

    Below shell shows how to query all unpublished duplicate rule from TestDuplicateRule soluition and then publish all of them.

    # Change below values to match your environment
    $clientId = "your-client-id"
    $clientSecret = "your-client-secret"
    $tenantId = "your-tenant-id"
    $resource = "your-org-url" # Sample: https://myorg.crm5.dynamics.com/
    
    # Get the access token
    $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -ContentType "application/x-www-form-urlencoded" -Body @{
      grant_type    = "client_credentials"
      client_id     = $clientId
      client_secret = $clientSecret
      scope         = "$resource/.default"
    }
    
    $accessToken = $tokenResponse.access_token
    
    # Define the solution name
    $solutionName = 'TestDuplicateRule' # Replace with your solution name
    
    # Fetch duplicate detection rules in the specified solution
    $fetchXml = @"
    <fetch>
    <entity name='duplicaterule'>
      <attribute name='duplicateruleid' />
      <filter>
        <condition attribute='statecode' operator='ne' value='1' />
      </filter>
      <link-entity name='solutioncomponent' from='objectid' to='duplicateruleid' link-type='inner'>
        <link-entity name='solution' from='solutionid' to='solutionid' link-type='inner'>
          <filter>
            <condition attribute='uniquename' operator='eq' value='$solutionName' />
          </filter>
        </link-entity>
      </link-entity>
    </entity>
    </fetch>
    "@
    
    # Encode the FetchXML query
    $encodedFetchXml = [System.Web.HttpUtility]::UrlEncode($fetchXml)
    
    # Fetch duplicate rules using the Web API
    $fetchUrl = "$resource/api/data/v9.2/duplicaterules?fetchXml=$encodedFetchXml"
    $duplicateRulesResponse = Invoke-RestMethod -Method Get -Uri $fetchUrl -Headers @{ Authorization = "Bearer $accessToken" }
    
    # Publish each duplicate rule
    foreach ($rule in $duplicateRulesResponse.value) {
      $ruleId = $rule.duplicateruleid
    
      # Create the payload
      $payload = @{
          entity = @{
              "@odata.type" = "Microsoft.Dynamics.CRM.duplicaterule"
              duplicateruleid = $ruleId
          }
      } | ConvertTo-Json
    
      # Call the PublishDuplicateRule action
      $publishUrl = "$resource/api/data/v9.2/duplicaterules($ruleId)/Microsoft.Dynamics.CRM.PublishDuplicateRule"
      Invoke-RestMethod -Method Post -Uri $publishUrl -Headers @{ Authorization = "Bearer $accessToken" } -ContentType "application/json" -Body $payload
    }