PowerShell Export-csv writes empty string for a NULL database value. Can it be told to write nothing?
Import-Csv
always returns blank strings, but there are plenty of ways to set those values to $null
if they're empty. For example, here I check for blank values before joining them:
Import-Csv a.csv | ForEach-Object {
# convert empty strings to null
$allValues = '"' + (($_.Psobject.Properties.Value | ForEach-Object {
if($_){"'$_'"} else{''} }) -join ',') + '"'
Invoke-Sqlcmd ("INSERT INTO TableATemporary VALUES $allValues")
}
Now it no longer sets empty strings in $allvalues
:
"'1','Joe',,'Sales'"
I recommend using Write-SqlTableData
for importing rather than running sqlcmd for each row, but it's just an efficiency thing.