microsoft / SQLServerPSModule

This repo is the home of SQL Server PowerShell Module development.
MIT License
45 stars 1 forks source link

Data conversion error while writing table with Write-SqlTableData #62

Closed andreiv3103 closed 8 months ago

andreiv3103 commented 8 months ago

I am trying to write to an SQL table an array of PsObjects. The write process exits with the following error:

Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.IConvertible'.Couldn't store <01-01-1970 05:30:00> in Last check-in Column. Expected type is DateTime.

The problem is that the column the error refers to, 'Last check-in' is definitely a [DateTime] data type. It is defined like this:

        @{ ## 'Last check-in'
            N = 'Last check-in'
            E = {
                if ([string]::IsNullOrWhiteSpace($_.LastSyncDateTime)) {
                    [datetime]'1970-01-01'
                }
                else {
                    [datetime]($_.LastSyncDateTime)
                }
            }
        }

So it cannot be any other data type. And definitely not a 'System.Management.Automation.PSObject'. If "$_.LastSyncDateTime" would be of a different type, the script would crash. But it doesn't.

I tried all I can think of but I cannot find the issues.

I am writing another table, in exactly the same way, without any issues.

Any idea is more than welcome.

andreiv3103 commented 8 months ago

I fixed it. I am going to write my findings here, in case someone else ends up in the same spot. Looks like the cmdlet does not know how to handle the PowerShell [datetime] type. So I converted the [datetime] to [string] and it works perfectly. The string format I used is the ISO one: 'yyyy-MM-ddTHH:mm:ss.mmZ'