So I am uploading csv data from a specific file in a folder on my desktop into a SQL Server database using Powershell and some rows will upload just fine however the majority are returning the following error
"Exception calling "ExecuteNonQuery" with "0" argument(s): "Conversion failed when converting date and/or time from character string." At line:3 char:5
-
$sqlCommand.ExecuteNonQuery() -
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- CategoryInfo : NotSpecified: (:) [], MethodInvocationException
- FullyQualifiedErrorId : SqlException"
I know it's an issue converting one of the columns containing a date however I'm not sure how to go about fixing it. Any help is appreciated. The script is as follows:
# Define variables
$serverName = "TDALYW10"
$databaseName = "ScriptTest"
$tableName = "VehicleStock"
$csvPath = "C:\Users\TDaly\Desktop\PowerShellTest2\vehicleStock.csv"
# Create a new SQL Server connection
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$serverName;Database=$databaseName;Integrated Security=True"
# Open the SQL Server connection
$sqlConnection.Open()
# Create a new SQL Server command
$sqlCommand = New-Object System.Data.SqlClient.SqlCommand
$sqlCommand.Connection = $sqlConnection
# Read the CSV file
$csv = Import-Csv $csvPath
# Loop through each row in the CSV file and insert it into the SQL Server table
foreach ($row in $csv) {
$sqlCommand.CommandText = "INSERT INTO $tableName (branch, stockNo, reg, category, make, model, variant, buyInSP, purchaseInvDate, dateIn, purchaseInvRef, odometer, clock, qual, [Base & Delivery], Overallowance, WriteDown, Sublet, PDI, Accessory, Bonus, [Motor Tax], [House Charge], Finance, Other, Previous, totalCost, purchaseAmt, purchaseVAT, retail, trade, VRT, VIBE, fuel, cc, body, colour, trim, owners, year, regDate, class, transm, [new/used], daysInStock, lastMOT, nextMOT) VALUES ('$($row.branch)', '$($row.stockNo)', '$($row.reg)', '$($row.category)', '$($row.make)', '$($row.model)', '$($row.variant)', '$($row.buyInSP)', '$($row.purchaseInvDate)', '$($row.dateIn)', '$($row.purchaseInvRef)', '$($row.odometer)', '$($row.clock)', '$($row.qual)', '$($row.'Base & Delivery')', '$($row.Overallowance)', '$($row.WriteDown)', '$($row.Sublet)', '$($row.PDI)', '$($row.Accessory)', '$($row.Bonus)', '$($row.'Motor Tax')', '$($row.'House Charge')', '$($row.Finance)', '$($row.Other)', '$($row.Previous)', '$($row.totalCost)', '$($row.purchaseAmt)', '$($row.purchaseVAT)', '$($row.retail)', '$($row.trade)', '$($row.VRT)', '$($row.VIBE)', '$($row.fuel)', '$($row.cc)', '$($row.body)', '$($row.colour)', '$($row.trim)', '$($row.owners)', '$($row.year)', '$($row.regDate)', '$($row.class)', '$($row.transm)', '$($row.'new/used')', '$($row.daysInStock)', '$($row.lastMOT)', '$($row.nextMOT)')"
$sqlCommand.ExecuteNonQuery()
}
# Close the SQL Server connection
$sqlConnection.Close()
```