Quantcast
Channel: SQLServerCentral » Programming » Powershell » Latest topics
Viewing all articles
Browse latest Browse all 467

Insert xml data into SQL server via SqlBulkCopy with powershell (casting error)

$
0
0
I tried to strip down this example to make it as terse as possible so it would be easy to read\answer.I'm getting a "cast not valid" error when trying to insert a data table containing xml using sqlbulckcopy.I cast the DataColumn that will hold the xml data to type System.Xml.XmlNode is that incorrect? Looking [url=http://msdn.microsoft.com/en-us/library/cc716729.aspx]here [/url]it just says the .NET Framework type is xml.Here an example of some xml data (located in C:\test\test.xml) I want to insert:<!-- Edited by XMLSpy® --><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>Here is the script I am using to try and insert it:[quote]$SQLDBName = 'test'$SQLServer = 'myserver,1433' #Open connection to sql DB$connectionString = "Server = $SQLServer;Integrated Security=true;Initial Catalog=$SQLDBName;"#$connectionString = "Server = $SQLServer;Data Source=SQLSERVER;Integrated Security=true;Initial Catalog=$SQLDBName;"$SQLConnection = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString$SQLConnection.DestinationTableName = "ForwardedEvents"#create columns for datatable and set their types$columns = @()$columns += #Order MUST match that of the DB(New-Object System.Data.DataColumn -ArgumentList @("EventLogXML" , [System.Xml.XmlNode] ))#build datatable for bulk insert$dt = New-Object System.Data.DataTable$columns | %{$dt.Columns.add($_) | Out-Null}$row = $dt.NewRow() #Create row$row.Item("EventLogXML") = [xml](cat C:\test\test.xml)$dt.Rows.Add($row) #add row to table#insert into DB and close connection$SQLConnection.WriteToServer($dt)$SQLConnection.close()[/quote]Running this script I get the following error:[quote]Exception calling "WriteToServer" with "1" argument(s): "Specified cast is not valid."[/quote]

Viewing all articles
Browse latest Browse all 467

Trending Articles