PowerShell function to search CRM 2011 for and Entity (via REST/oData)

I wrote about how to retrieve records from CRM 2011 via oData. I wanted to wrap that up in a function that I can use to do a quick search:


Function JBMURPHY-CRM-SearchEntity{
PARAM([parameter(Mandatory=$true)][ValidateSet("Contact", "Account","SystemUser")]$EntityType,[parameter(Mandatory=$true)]$SearchString,[parameter(Mandatory=$true)]$SearchField,$FieldsToReturn)
$assembly = [Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
$baseurl="http://crmserver.company.com/Organization/xrmservices/2011/OrganizationData.svc"
$urlparams="/$($EntityType)Set?`$filter=substringof('$($SearchString)',$($SearchField))"
$url=$baseurl+$urlparams
$Count=0
while ($url){
    $webclient = new-object System.Net.WebClient
    $webclient.UseDefaultCredentials = $true
    $webclient.Headers.Add("Accept", "application/json")
    $webclient.Headers.Add("Content-Type", "application/json; charset=utf-8");
    $dataString=$webclient.DownloadString($url)
    $json=new-object System.Web.Script.Serialization.JavaScriptSerializer
    $data=$json.DeserializeObject($dataString)
    foreach ($result in $data.d.results){
            $Count=$Count+1
            write-host -NoNewline "$Count. "
            foreach ($field in $FieldsToReturn){
            write-host -NoNewline "$field : "
            Write-Host -NoNewline $result."$field"
            Write-Host -NoNewline ", "
            #write-host "$($result.FullName) , $($result.EMailAddress1)"
            }
            Write-Host
    }
    if ($data.d.__next){
        $url=$data.d.__next.ToString()
    }
    else {
        $url=$null
    }
}
}

And to use this function:

JBMURPHY-CRM-SearchEntity -EntityType Account -SearchField Name -SearchString “Sard” -FieldsToReturn Name,AccountId

,

Comments are closed.

Powered by WordPress. Designed by WooThemes