I'm trying to use a Powershell-script to build a connection with Microsoft Dynamics CRM. In some others scripts I want to use this connection. If I export the connection-object, I can't use it as connection-object.
I return the object with:
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $connection = New-Object Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy($organizationUri,$null,$clientCredentials,$null)
[Microsoft.Xrm.Sdk.Entity] $systemUser = $connection.Retrieve("systemuser", $userId, (New-Object Microsoft.Xrm.Sdk.Query.ColumnSet(@("firstname", "lastname"))))
return $connection
And this is, how I call the script above:
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = (New-CRMConnection -server $connectionjson.server -organization $connectionjson.organization -domain $connectionjson.domain -user $connectionjson.username -password $connectionjson.password)
But I get this error (I translated it from german, so it's not the exact error-message):
The value "System.Object[]" from type "System.Object[]" cannot be converted to "Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy".
In C:\Users\drieke\Documents\git\SNC-CRM\Solution\Import-CRMSolution.ps1:19 Zeichen:5
+ [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
How do I correctly return my object?
EDIT
My problem was, that my function returned an array. The first Object in the array is the object i need. So my solution is the [1] in following code:
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = (New-CRMConnection -server $connectionjson.server -organization $connectionjson.organization -domain $connectionjson.domain -user $connectionjson.username -password $connectionjson.password)[1]
The error message means that New-CRMConnection
returns an array of objects. Conversion from array into some other non-collection object makes no sense, so Powershell complains.
To debug the scenario, first save New-CRMConnection
's return value into a variable and work from there.
$connections = (New-CRMConnection -server $connectionjson.server `
-organization $connectionjson.organization -domain $connectionjson.domain `
-user $connectionjson.username -password $connectionjson.password)
# What kind of object is connections?
$connections.GetType()
# If it was an array, let's see its 1st element
$c = $connections[0]
# What kind of object is the first element?
$c.GetType()
# If it looks sensible, try casting
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = $c