For my previous question, I implemented the solution from this SO link. I used the .NET libraries and used the two functions Out-DataTable and Write-DataTable in my solution.
Currently, I have my CSVs
in place and using the Out-DataTable
and Write-DataTable
functions to insert data into SQL Server. However, it is not working with date
data types. I get the error -
Write-DataTable : System.Management.Automation.MethodInvocationException: Exception calling "WriteToServer" with "1" argument(s): "The given value of type String from the data source cannot be converted to type date of the specified target column." --->
System.InvalidOperationException: The given value of type String from the data source cannot be converted to type date of the specified target column. ---> System.FormatException: Failed to convert parameter value from a String to a DateTime. ---> System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.Convert.ToDateTime(String value, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming)
So when I looked into Out-DataTable
function, it has another function named Get-Type
defined in it, which basically does the column type conversion. Here is the function Get-Type
-
function Get-Type
{
param($type)
$types = @(
'System.Boolean',
'System.Byte[]',
'System.Byte',
'System.Char',
'System.Datetime',
'System.Decimal',
'System.Double',
'System.Guid',
'System.Int16',
'System.Int32',
'System.Int64',
'System.Single',
'System.UInt16',
'System.UInt32',
'System.UInt64')
if ( $types -contains $type ) {
Write-Output "$type"
}
else {
Write-Output 'System.String'
}
} #Get-Type
Now SQL has a data type as date other than the .NET's datetime
function. Hence, I am running into this error.
I had a thought of using parseexact
method, but that again doesn't resolve the issue, since it resolves to type string
. Also, Import-Csv
takes in a flat file, hence the date in the format yyyy-MM-dd
will always be of type string
and my code would fail inevitably.
I have looked for a solution at this and this link, but I am not able to figure it out how to convert the string type into date. Any help will be much appreciated. Also, let me know if any extra info is required.