I was working on a PowerShell script, and I just could not get past the error below:
“Element ‘http://schemas.datacontract.org/2004/07/System.Collections.Generic:value’ contains data from a
type that maps to the name ‘System.Management.Automation:PSObject’. The deserializer has no knowledge of any type that
maps to this name”
Yet I was not trying to do anything extraordinary (other than writing a PowerShell script which is something I had not really done before).
In a nutshell, I would create a connection in my script, then I would create an entity, and, then, set an EntityReference attribute there (it is not a working code below – it’s a simplified sample):
$conn = Get-CrmConnection
$entity = New-Object Microsoft.Xrm.Sdk.Entity -ArgumentList $entityName
$value = New-Object -TypeName Microsoft.Xrm.Sdk.EntityReference
…
$entity[$name] = $value
$conn.Update($entity)
The error would be happening in the Update call above.
If you do a search for the error above, you’ll see a few references. It still took me more than a day to figure out a workaround!
Turned out there is something with boxing/unboxing of objects between PowerShell and .NET which I really don’t fully understand at the moment, but, once I realized that, I figured what if I just bypassed boxing / unboxing alltogether. It worked in my case – what I had to do is:
Define a helper class
$HelperSource = @”
public class Helper
{
public static void SetAttribute(Microsoft.Xrm.Sdk.Entity entity, string name, object value)
{
entity[name] = value;
}
}
“@
Define a helper function
You might not need it, by the way. It depends on how the script is structured – I had to use it in another class, and, so, my Helper class would not be available to the compiler yet.. unlike the function below:
function Set-Attribute($entity, $name, $value)
{
[Helper]::SetAttribute($entity, $name, $value)
}
Add that helper class to my PowerShell script
$assemblyDir = Get-Location
$refs = @”$assemblyDir\Microsoft.Xrm.Sdk.dll”,”System.Runtime.Serialization.dll”,”System.ServiceModel.dll”)
Add-Type -TypeDefinition $script:HelperSource -ReferencedAssemblies $refs
Now, instead of using $entity[$name] = $value, I can use Set-Attribute($entity, $name, $value).
Seems to be working so far – I’m getting all my entity references updated correctly.