Error Serializing Value Of Type System.data.datatable.

I'm building a Web Service with the CLR 2.0 that returns a DataTable but I get the followng error: System.InvalidOperationException: There was an error generating the XML.

Active5 years, 9 months ago

I'm trying to save and load a DataTable in PowerShell.I save it like this:

and load it like this:

Could not cast value of type nsmanagedobject_

But the type I get back is an array of Rows rather than a DataTable!This is causing me major problems as it needs to be passed into a function which requires a DataTable, and it cannot be cast to one.

Any help greatly appreciated, thanks.

Benjamin
16.9k31 gold badges133 silver badges244 bronze badges
ChrisChris

1 Answer

This is a known trap: PowerShell processes your DataTable as a collection of DataRow items. That is the very first command

already “forgets” the data table. You may take a look at the output file, it starts with DataRow:

To avoid this effect, use the , operator (it looks funny but that’s exactly how it works):

As a result, the output file now starts with DataTable:

After that you can import the table back:

Let’s check it:

We can see the same effect (DataRow instead of DataTable). Thus, the correct command is with ,:

So, we really dehydrate a DataTable in this way.

Error Serializing Value 'table 1' Of Type 'system.data.datatable

EDIT: This effect is known as unrolling. PowerShell tends to unroll collections. The comma operator creates an array of a single item. PowerShell unrolls this array, too, but it does not unroll its items (our DataTable).

Here is a very similar question:

Community
Roman KuzminRoman Kuzmin

Unable To Create A Constant Value Of Type

31.6k8 gold badges78 silver badges102 bronze badges
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.

Error Serializing Value 'table' Of Type 'system.data.datatable.'

Not the answer you're looking for? Browse other questions tagged powershellxml-serializationdatatablexml-deserialization or ask your own question.