serving the solutions day and night

Pages

Thursday, November 9, 2017

PowerShell - MS Dynamics CRM CRUD Operations

Please refer Read App.Config -
Please refer Connect MS Dynamics CRM

$crm_service = Invoke-CRMConn -OrganizationUrl $crm_organization_url -UserName $crm_username -Password $crm_password

## 1. To test the connection, check who you are:
function WhoAMI() {
    $request = new-object Microsoft.Crm.Sdk.Messages.WhoAmIRequest
    $crm_service.Execute($request)

    <#
    UserId         : 0dc96a70-952d-e611-80f0-0050568c6c1c
    BusinessUnitId : a6099f28-952d-e611-80ec-0050568c6c1c
    OrganizationId : 0d67a31e-952d-e611-80ec-0050568c6c1c
    ResponseName   : WhoAmI
    Results        : {[UserId, 0dc96a70-952d-e611-80f0-0050568c6c1c], [BusinessUnitId, a6099f28-0caf-e611-80ec-0050568c6c1c],
                     [OrganizationId, 0d67a31e-0caf-e611-80ec-0050568c6c1c]}
    ExtensionData  : System.Runtime.Serialization.ExtensionDataObject
    #>
}



## 2. Query for all existing contact details
function GetList() {
    $account_qry = New-Object Microsoft.Xrm.Sdk.Query.QueryExpression("account")
    $account_qry.ColumnSet = New-Object Microsoft.Xrm.Sdk.Query.ColumnSet("name", "accountnumber", "industrycode", "parentaccountid", "ownerid", "statecode", "statuscode")
    #$account_qry.Criteria.AddCondition("industrycode", [Microsoft.Xrm.Sdk.Query.ConditionOperator]::NotNull);
    #$account_qry.Criteria.AddCondition("accountnumber", [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Equal, 'LANG016');
    $account_qry.AddOrder("name", [Microsoft.Xrm.Sdk.Query.OrderType]::Ascending);

    ## RetrieveMultiple returns a maximum of 5000 records by default.
    ## If you need more, use the response's PagingCookie.
    $account_response = $crm_service.RetrieveMultiple($account_qry)

    ## create a dictionary that maps each account key is (name, accountnumber) & id is accountid:
    $account_dic = @{ }
    $account_response.Entities | ForEach-Object {
        $name = $_.Attributes["name"];
        $accountnumber = $_.Attributes["accountnumber"];
        $industrycode = $_.Attributes["industrycode"].value
        $statecode = $_.Attributes["statecode"].value
        $statuscode = $_.Attributes["statuscode"].value
        $parentaccountid = $_.Attributes["parentaccountid"] ## $parentaccountid.Id
        $ownerid = $_.Attributes["ownerid"]
        $value = ("{0}|{1}|{2}|{3}|{4}|{5}|{6}" -f @($name, $accountnumber, $industrycode, $parentaccountid.Name, $ownerid.Name, $statecode, $statuscode))
        $account_dic.Add($_.Id, $value)
    }

    ## account_dic contact values
    $account_dic.GetEnumerator() | ForEach-Object{
        $account = 'Account {0} -  {1}' -f $_.key, $_.value
        Write-Output $account
    }

    <#
        Account efe7e3ac-9fc5-e711-80f7-0050568c5bd0 -  SQL Server|LANG200|18|C#|UAT|0|1
        Account dc57a4c1-8bc5-e711-80f7-0050568c5bd0 -  PowerShell|LANG016|8||DNS|1|2
    #>
}

## 3. Insert new entity record
function InsertEntity() {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory=$true)] [string]$Name,
        [Parameter(Position=1, Mandatory=$true)] [string]$AccountNumber,
        [Parameter(Position=2, Mandatory=$false)] [string]$IndustryCode,
        [Parameter(Position=3, Mandatory=$false)] [string]$ParentAccountID
    )
 
    try {
        $account = New-Object Microsoft.Xrm.Sdk.Entity("account")
        $account.Attributes["name"] = $Name
        $account.Attributes["accountnumber"] = $AccountNumber
        if ($IndustryCode.Length -gt 0) {
            $industry_code_os = New-Object Microsoft.Xrm.Sdk.OptionSetValue($IndustryCode)
            $account.Attributes["industrycode"] = [Microsoft.Xrm.Sdk.OptionSetValue] $industry_code_os
        }
        if ($ParentAccountID.Length -gt 0) {
            $account_ef = New-Object Microsoft.Xrm.Sdk.EntityReference('account', $ParentAccountID);
            $account.Attributes["parentaccountid"] = [Microsoft.Xrm.Sdk.EntityReference]$account_ef;
        }

        $crm_service.Create($account)
    }
    catch [Exception] {
        echo $_.Exception.Message
    }

    <#
        Guid                             
        ----                             
        54fad01a-a0c5-e711-80f7-0050568c5bd0
    #>
}

## 4. Update existing entity record
function UpdateEntity() {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory=$true)] [string]$ID,
        [Parameter(Position=1, Mandatory=$true)] [string]$Name,
        [Parameter(Position=2, Mandatory=$true)] [string]$AccountNumber,
        [Parameter(Position=3, Mandatory=$false)] [string]$IndustryCode,
        [Parameter(Position=4, Mandatory=$false)] [string]$ParentAccountID
    )
 
    try {
        $account = New-Object Microsoft.Xrm.Sdk.Entity("account")
        $account.Id = $ID
        $account.Attributes["name"] = $Name
        $account.Attributes["accountnumber"] = $AccountNumber
        if ($IndustryCode.Length -gt 0) {
            $industry_code_os = new-object Microsoft.Xrm.Sdk.OptionSetValue($IndustryCode)
            $account.Attributes["industrycode"] = [Microsoft.Xrm.Sdk.OptionSetValue] $industry_code_os
        }
        if ($ParentAccountID.Length -gt 0) {
            $account_ef = New-Object Microsoft.Xrm.Sdk.EntityReference('account', $ParentAccountID);
            $account.Attributes["parentaccountid"] = [Microsoft.Xrm.Sdk.EntityReference]$account_ef;
        }

        $crm_service.Update($account)
    }
    catch [Exception] {
        echo $_.Exception.Message
    }
}

## 5. Delete existing entity record
function DeleteEntity() {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory=$true)] [string]$ID
    )
 
    try {
        $crm_service.Delete('account', $ID)
    }
    catch [Exception] {
        echo $_.Exception.Message
    }
}

## 6. Change owner
function AssignOwner() {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory=$true)] [string]$SystemUserID,
        [Parameter(Position=1, Mandatory=$true)] [string]$AccountID
    )
 
    try {
        $team_ef = New-Object Microsoft.Xrm.Sdk.EntityReference('systemuser', $SystemUserID);
        $account_ef = New-Object Microsoft.Xrm.Sdk.EntityReference('account', $AccountID);
     

        $request = New-Object Microsoft.Crm.Sdk.Messages.AssignRequest;
        $request.Assignee = $team_ef;
        $request.Target = $account_ef;
        $crm_service.Execute($request)
    }
    catch [Exception] {
        echo $_.Exception.Message
    }

    <#
        ResponseName Results ExtensionData                                 
        ------------ ------- -------------                                 
        Assign       {}      System.Runtime.Serialization.ExtensionDataObject
    #>
}

## 7. Change state & status of existing record
function ChangeStatus(){
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory=$true)] [string]$AccountID,
        [Parameter(Position=1, Mandatory=$true)] [string]$State,
        [Parameter(Position=2, Mandatory=$true)] [string]$Status
    )
 
    try {

        $request = New-Object Microsoft.Crm.Sdk.Messages.SetStateRequest;
        $account_ef = New-Object Microsoft.Xrm.Sdk.EntityReference('account', $AccountID);
     
        $request.EntityMoniker   = $account_ef;
        $request.State  = New-Object Microsoft.Xrm.Sdk.OptionSetValue($State);
        $request.Status = New-Object Microsoft.Xrm.Sdk.OptionSetValue($Status);

     
        $crm_service.Execute($request)
    }
    catch [Exception] {
        echo $_.Exception.Message
    }
    <#
        ResponseName Results ExtensionData                                 
        ------------ ------- -------------                                 
        Assign       {}      System.Runtime.Serialization.ExtensionDataObject
    #>
}

WhoAMI
GetList
InsertEntity -Name 'SQL Server' -AccountNumber 'LANG200' -IndustryCode 18 -ParentAccountID '0000a7d7-0000-0000-0000-082e5f2a3b8c'
UpdateEntity -ID '00000991-0000-0000-0000-0050568c5bd0' -Name 'C#' -AccountNumber 'LANG004' -ParentAccountID '0000a7d7-0000-0000-0000-082e5f2a3b8c'
DeleteEntity -ID '000032a2-0000-0000-0000-0050568c5bd0'
AssignOwner -SystemUserID '000077A8-0000-0000-0000-0050568C2FC0' -AccountID '0000a4c1-0000-0000-0000-0050568c5bd0'
ChangeStatus -AccountID '0000a4c1-0000-0000-0000-0050568c5bd0' -State '1' -Status '2'

No comments: