PowerShell Dynamics CRM: Lookup Account ID using Account Name

Back to Index

Gets the accountid by name.

Documentation: http://www.odata.org/getting-started/basic-tutorial/#queryData

CURL Command

curl -X GET https://my-dynamics-domain.api.crm.dynamics.com/api/data/v9.0/accounts
  -H "Accept: application/json" \
  -H "OData-MaxVersion: 4.0"  \
  -H "OData-Version: 4.0" \
  -d "$select=accountid" \
  -d "$filter=name eq 'Blue Yonder Airlines'" \
  -H "Authorization: Bearer DYNAMICS_CRM_ACCESS_TOKEN"

PowerShell Example

[Reflection.Assembly]::LoadFile("C:\myAssemblies\ChilkatDotNet2.dll")

$rest = New-Object Chilkat.Rest

#  URL: https://my-dynamics-domain.api.crm.dynamics.com/api/data/v9.0/accounts
$bTls = $true
$port = 443
$bAutoReconnect = $true
$success = $rest.Connect("my-dynamics-domain.api.crm.dynamics.com",$port,$bTls,$bAutoReconnect)
if ($success -ne $true) {
    $("ConnectFailReason: " + $rest.ConnectFailReason)
    $($rest.LastErrorText)
    exit
}

$rest.AddQueryParam("$select","accountid")
$rest.AddQueryParam("$filter","name eq 'Blue Yonder Airlines'")

$rest.AddHeader("OData-MaxVersion","4.0")
$rest.AddHeader("Accept","application/json")
$rest.AddHeader("OData-Version","4.0")
$rest.AddHeader("Authorization","Bearer DYNAMICS_CRM_ACCESS_TOKEN")

$sbResponseBody = New-Object Chilkat.StringBuilder
$success = $rest.FullRequestNoBodySb("GET","/api/data/v9.0/accounts",$sbResponseBody)
if ($success -ne $true) {
    $($rest.LastErrorText)
    exit
}

$respStatusCode = $rest.ResponseStatusCode
if ($respStatusCode -ge 400) {
    $("Response Status Code = " + $respStatusCode)
    $("Response Header:")
    $($rest.ResponseHeader)
    $("Response Body:")
    $($sbResponseBody.GetAsString())
    exit
}

$jsonResponse = New-Object Chilkat.JsonObject
$jsonResponse.LoadSb($sbResponseBody)

$odataContext = $jsonResponse.StringOf("`"@odata.context`"")
$i = 0
$count_i = $jsonResponse.SizeOfArray("value")
while ($i -lt $count_i) {
    $jsonResponse.I = $i
    $odataEtag = $jsonResponse.StringOf("value[i].`"@odata.etag`"")
    $accountid = $jsonResponse.StringOf("value[i].accountid")
    $i = $i + 1
}

Sample JSON Response Body

{
  "@odata.context": "https://mydomain.api.crm.dynamics.com/api/data/v9.0/$metadata#accounts(accountid)",
  "value": [
    {
      "@odata.etag": "W/\"1817216\"",
      "accountid": "aca19cdd-88df-e311-b8e5-6c3be5a8b200"
    }
  ]
}