Powershell Dynamics CRM, как добавить две очереди пользователю - PullRequest
0 голосов
/ 07 января 2019

Я создал пользователя и пытаюсь назначить ему две очереди № 1 и № 2. Проблема в том, что код, который я использовал, заменяет только последнюю очередь.

Import-Module C:\Powershell\CRMBuzz\CRMBuzzPowerTools_Module_2_0_0_15_Setup\WindowsPowerShell\Modules\CRMBuzzPowerTools\CRMBuzz.PowerTools.PSSnapin.dll -Force -WarningAction SilentlyContinue -DisableNameCheckin
$connString="Url=https://crmlab:5555/CRMLab;Username=test@crm.lab;password=******;"
$CRMConn = New-OrganizationConnection -ConnectionString $connString -Verbose
$queue_ref0=Get-EntityReferenceByName -OrganizationService $CRMConn -EntityName "queue" -FindFieldName "name" -ReferenceValue "TEST1"
$queue_ref1=Get-EntityReferenceByName -OrganizationService $CRMConn -EntityName "queue" -FindFieldName "name" -ReferenceValue "TEST2"
$userent=Search-EntityFull -OrganizationService $CRMConn  -EntityObject systemuser -FieldName domainname -SearchValue "TEST\P_TEST"
[Microsoft.Xrm.Sdk.EntityReference] $userent.Attributes["queueid"]=$queue_ref0
[Microsoft.Xrm.Sdk.EntityReference] $userent.Attributes["queueid"]=$queue_ref1
Update-Record -OrganizationService $CRMConn -EntityObject $userent –verbose

Я попробовал другой метод, который нашел в Интернете, но он возвращает ошибки несовместимости.

Move-CrmRecordToQueue -EntityLogicalName account -Id 5ff140ea-95ed-e811-80e9-005056bd633b -QueueName "TEST1" -WorkingUserId 5bf140ea-95ed-e811-80e9-005056bd633b

Я тоже пробовал это, но не знаю параметров для использования.

Import-Module C:\Powershell\Handy.Crm.Extensions.Powershell.Cmdlets
$cred = Get-Credential
$CRMConn = Connect-CrmOnPremDiscovery -Credential $cred -ServerUrl https://crmlab:5555/CRMLab
Set-CRMQueueForUser -Connection $CRMConn -UserId 5bf140ea-95ed-e811-80e9-005056bd633b -QueueId 023963ca-08a5-e611-80c6-00155d011760

EDIT

Ответ Джеймса прояснил несколько вещей для меня. Выше я пытался добавить две очереди в очередь пользователя по умолчанию, что невозможно. Я думаю, что я должен добавить их в поле, которое находится ниже очереди по умолчанию, как на этом рисунке (не знаю имя этого поля):

enter image description here

Ответы [ 3 ]

0 голосов
/ 10 января 2019

Похоже, вы пытаетесь добавить пользователя в очередь.

Уверен, что этот раздел называется "Очереди, в которых я участвую", что является queuemembership_association отношением многих ко многим между пользователем и очередью.

Вам нужно будет выдать AssociateRequest .

0 голосов
/ 16 января 2019

Да, вы можете сделать это с PowerShell .

Например, ссылка queuemembership_association может быть создана с помощью приведенного ниже командлета. (Просьба проверить это, поскольку я еще не проверял это)

PS C:\>$systemuser = Get-CrmRecord systemuser 00005a70-6317-e511-80da-c4346bc43d94 name

 PS C:\>$queue = Get-CrmRecord queue 66005a70-6317-e511-80da-c4346bc43d94 fullname

 PS C:\>Add-CrmRecordAssociation $systemuser $queue queuemembership_association

Доступны две функции для привязки одной записи объекта и массового связывания, а именно Add-CrmRecordAssociation и Add-CrmMultiRecordAssociation. Вставка связанных командлетов вместе с примерами:

#CreateEntityAssociation
function Add-CrmRecordAssociation{

<#
 .SYNOPSIS
 Associates two records for N:N relationship.

 .DESCRIPTION
 The Add-CrmRecordAssociation cmdlet lets you associate two records for N:N relationship by specifying relatioship logical name. 

 There are two ways to specify records.
 
 1. Pass EntityLogicalName and record's Id for both records.
 2. Get a record object by using Get-CrmRecord/Get-CrmRecords cmdlets, and pass it for both records.

 You can specify relationship logical name for the association.

 .PARAMETER conn
 A connection to your CRM organizatoin. Use $conn = Get-CrmConnection <Parameters> to generate it.

 .PARAMETER CrmRecord1
 A first record object which is obtained via Get-CrmRecord/Get-CrmRecords. When you pass CrmRecord, then you don't use EntityLogicalName/Id.

 .PARAMETER CrmRecord2
 A second record object which is obtained via Get-CrmRecord/Get-CrmRecords. When you pass CrmRecord, then you don't use EntityLogicalName/Id.

 .PARAMETER EntityLogicalName1
 A logicalname for first Entity. i.e.)accout, contact, lead, etc..

 .PARAMETER Id1
 An Id (guid) of first record

 .PARAMETER EntityLogicalName2
 A logicalname for second Entity. i.e.)accout, contact, lead, etc..

 .PARAMETER Id2
 An Id (guid) of second record

 .PARAMETER RelationshipName
 A N:N relationship logical name.

 .EXAMPLE
 Add-CrmRecordAssociation -conn $conn -EntityLogicalName1 account -Id1 00005a70-6317-e511-80da-c4346bc43d94 -EntityLogicalName2 contact -Id2 66005a70-6317-e511-80da-c4346bc43d94 -RelationshipName new_accounts_contacts

 This example associates an account and a contact records through new_accounts_contacts custom N:N relationship.

 .EXAMPLE
 Add-CrmRecordAssociation account 00005a70-6317-e511-80da-c4346bc43d94 contact 66005a70-6317-e511-80da-c4346bc43d94 new_accounts_contacts
 
 This example associates an account and a contact records through new_accounts_contacts custom N:N relationship by ommiting parameters names.
 When ommiting parameter names, you do not provide $conn, cmdlets automatically finds it.

 .EXAMPLE
 PS C:\>$account = Get-CrmRecord account 00005a70-6317-e511-80da-c4346bc43d94 name

 PS C:\>$contact = Get-CrmRecord contact 66005a70-6317-e511-80da-c4346bc43d94 fullname

 PS C:\>Add-CrmRecordAssociation -conn $conn -CrmRecord1 $account -CrmRecord2 $contact -RelationshipName new_accounts_contacts

 This example retrieves and stores an account and a contact records to variables, then pass them to Add-CrmRecordAssociation cmdlets.

 .EXAMPLE
 PS C:\>$account = Get-CrmRecord account 00005a70-6317-e511-80da-c4346bc43d94 name

 PS C:\>$contact = Get-CrmRecord contact 66005a70-6317-e511-80da-c4346bc43d94 fullname

 PS C:\>Add-CrmRecordAssociation $account $contact new_accounts_contacts

 This example retrieves and stores an account and a contact records to variables, then pass them to Add-CrmRecordAssociation cmdlets.

#>

    [CmdletBinding()]
    PARAM(
        [parameter(Mandatory=$false)]
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]$conn,
        [parameter(Mandatory=$true, Position=1, ParameterSetName="CrmRecord")]
        [PSObject]$CrmRecord1,
        [parameter(Mandatory=$true, Position=2, ParameterSetName="CrmRecord")]
        [PSObject]$CrmRecord2,
        [parameter(Mandatory=$true, Position=1, ParameterSetName="NameWithId")]
        [string]$EntityLogicalName1,
        [parameter(Mandatory=$true, Position=2, ParameterSetName="NameWithId")]
        [guid]$Id1,
        [parameter(Mandatory=$true, Position=3, ParameterSetName="NameWithId")]
        [string]$EntityLogicalName2,
        [parameter(Mandatory=$true, Position=4, ParameterSetName="NameWithId")]
        [guid]$Id2,
        [parameter(Mandatory=$true, Position=5)]
        [string]$RelationshipName
    )

    $conn = VerifyCrmConnectionParam $conn; 

    if($CrmRecord1 -ne $null)
    {
        $EntityLogicalName1 = $CrmRecord1.logicalname
        $Id1 = $CrmRecord1.($EntityLogicalName1 + "id")
    }

    if($CrmRecord2 -ne $null)
    {
        $EntityLogicalName2 = $CrmRecord2.logicalname
        $Id2 = $CrmRecord2.($EntityLogicalName2 + "id")
    }

    try
    {
        $result = $conn.CreateEntityAssociation($EntityLogicalName1, $Id1, $EntityLogicalName2, $Id2, $RelationshipName, [Guid]::Empty)
        if(!$result)
        {
            return $conn.LastCrmException
        }
    }
    catch
    {
        return $conn.LastCrmException
    }
}

#CreateMultiEntityAssociation
function Add-CrmMultiRecordAssociation{

<#
 .SYNOPSIS
 Associates multiple records to single record for N:N relationship.

 .DESCRIPTION
 The Add-CrmMultiRecordAssociation cmdlet lets you associate multiple records to single record for N:N relationship by specifying relatioship logical name. 
 Use @('<object>','<object>') syntax to specify multiple ids or records.
 if the relationship is self-referencing, specify $True for -IsReflexiveRelationship Parameter.

 There are two ways to specify records.
 
 1. Pass EntityLogicalName and record's Id for both records.
 2. Get record object(s) by using Get-CrmRecord/Get-CrmRecords cmdlets, and pass them.

 You can specify relationship logical name for the association.

 .PARAMETER conn
 A connection to your CRM organizatoin. Use $conn = Get-CrmConnection <Parameters> to generate it.

 .PARAMETER CrmRecord1
 A first record object which is obtained via Get-CrmRecord/Get-CrmRecords. When you pass CrmRecord, then you don't use EntityLogicalName/Id.

 .PARAMETER CrmRecord2s
 An array of records object which are obtained via Get-CrmRecord/Get-CrmRecords. When you pass CrmRecord, then you don't use EntityLogicalName/Id.

 .PARAMETER EntityLogicalName1
 A logicalname for first Entity. i.e.)accout, contact, lead, etc..

 .PARAMETER Id1
 An Id (guid) of first record

 .PARAMETER EntityLogicalName2
 A logicalname for second Entity. i.e.)accout, contact, lead, etc..

 .PARAMETER Id2s
 An array of Ids (guid) of second records. Specify by using @('66005a70-6317-e511-80da-c4346bc43d94','62005a70-6317-e511-80da-c4346bc43d94') synctax.

 .PARAMETER RelationshipName
 A N:N relationship logical name.

 .PARAMETER IsReflexiveRelationship
 Specify $True if the N:N relationship is self-referencing.

 .EXAMPLE
 Add-CrmMultiRecordAssociation -conn $conn -EntityLogicalName1 account -Id1 00005a70-6317-e511-80da-c4346bc43d94 -EntityLogicalName2 contact -Id2s @('66005a70-6317-e511-80da-c4346bc43d94','62005a70-6317-e511-80da-c4346bc43d94') -RelationshipName new_accounts_contacts
 This example associates an account and two contact records through new_accounts_contacts custom N:N relationship.

 .EXAMPLE
 Add-CrmMultiRecordAssociation account 00005a70-6317-e511-80da-c4346bc43d94 contact @('66005a70-6317-e511-80da-c4346bc43d94','62005a70-6317-e511-80da-c4346bc43d94') new_accounts_contacts
 
 This example associates an account and two contact records through new_accounts_contacts custom N:N relationship by ommiting parameters names.
 When ommiting parameter names, you do not provide $conn, cmdlets automatically finds it.

 .EXAMPLE
 PS C:\>$account = Get-CrmRecord account 00005a70-6317-e511-80da-c4346bc43d94 name

 PS C:\>$fetch = @"
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false" no-lock="true">
  <entity name="contact">
    <attribute name="fullname" />
    <filter type="and">
      <condition attribute="lastname" operator="like" value="%sample%" />
    </filter>
  </entity>
</fetch>
"@

 PS C:\>$contacts = Get-CrmRecordsByFetch $fetch

 PS C:\>Add-CrmMultiRecordAssociation $account $contacts.CrmRecords new_accounts_contacts

 This example retrieves contacts by using FetchXML and stores to a variable, then retrieves and store an account record to another variable.
 Then passes those variables Add-CrmMultiRecordAssociation.
#>

    [CmdletBinding()]
    PARAM(
        [parameter(Mandatory=$false)]
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]$conn,
        [parameter(Mandatory=$true, Position=1, ParameterSetName="CrmRecord")]
        [PSObject]$CrmRecord1,
        [parameter(Mandatory=$true, Position=2, ParameterSetName="CrmRecord")]
        [PSObject[]]$CrmRecord2s,
        [parameter(Mandatory=$true, Position=1, ParameterSetName="NameWithId")]
        [string]$EntityLogicalName1,
        [parameter(Mandatory=$true, Position=2, ParameterSetName="NameWithId")]
        [guid]$Id1,
        [parameter(Mandatory=$true, Position=3, ParameterSetName="NameWithId")]
        [string]$EntityLogicalName2,
        [parameter(Mandatory=$true, Position=4, ParameterSetName="NameWithId")]
        [guid[]]$Id2s,
        [parameter(Mandatory=$true, Position=5)]
        [string]$RelationshipName,
        [parameter(Mandatory=$false, Position=6)]
        [bool]$IsReflexiveRelationship
    )

    $conn = VerifyCrmConnectionParam $conn;   

    if($CrmRecord1 -ne $null)
    {
        $EntityLogicalName1 = $CrmRecord1.logicalname
        $Id1 = $CrmRecord1.($EntityLogicalName1 + "id")
    }

    if($CrmRecord2s -ne $null)
    {
        if($CrmRecord2s.Count -ne 0)
        {
            $EntityLogicalName2 = $CrmRecord2s[0].logicalname
            $Ids = New-Object 'System.Collections.Generic.List[System.Guid]'
            foreach($CrmRecord2 in $CrmRecord2s)
            {
                $Ids.Add($CrmRecord2.($EntityLogicalName2 + "id"))
            }
            $Id2s = $Ids.ToArray()
        }
         else
        {
            Write-Warning 'CrmRecords2 does not include any records.'
            break;
        }
    }   

    try
    {
        $result = $conn.CreateMultiEntityAssociation($EntityLogicalName1, $Id1, $EntityLogicalName2, $Id2s, $RelationshipName, [Guid]::Empty, $IsReflexiveRelationship)
        if(!$result)
        {
            return $conn.LastCrmException
        }
    }
    catch
    {
        return $conn.LastCrmException
    }
}
0 голосов
/ 07 января 2019

Похоже, вы пытаетесь установить поле очереди по умолчанию.

enter image description here

Это может содержать только одно значение за раз, поэтому я не думаю, что то, что вы пытаетесь сделать, сработает.

Если это полезно, вы можете выполнить вызов обновления дважды, это сохранит оба значения в CRM, но последнее заменит первое.

[Microsoft.Xrm.Sdk.EntityReference] $userent.Attributes["queueid"]=$queue_ref0
Update-Record -OrganizationService $CRMConn -EntityObject $userent –verbose

[Microsoft.Xrm.Sdk.EntityReference] $userent.Attributes["queueid"]=$queue_ref1
Update-Record -OrganizationService $CRMConn -EntityObject $userent –verbose
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...