3
votes

I would like to import data from my CSV files using PowerShell. The answer posted here: How to import data from .csv in SQL Server using PowerShell? works like a charm.

However, I'd like to build on this solution. If the files contain 2 columns, e.g. Feature1, Feature2, I'd like the table to have a third column e.g. Name. The aim is to load multiple files corresponding to different Names into a single table.

Feature1 | Feature2 | Name
Value1   | Value2   | NameA
Value3   | Value4   | NameA
...
Value5   | Value6   | NameB

If I give PowerShell the variable

$NameValue = "NameA"

How do I include this correctly in the command:

Import-CSV .\NameA.csv | ForEach-Object {Invoke-Sqlcmd `
  -Database $database -ServerInstance $server `
  -Query "insert into $table VALUES ('$($_.Feature1)','$($_.Feature2)', '$($NameValue.Name)')"
  }

Currently, this just fills in the Feature columns, but the Name column is blank.

1
just $NameValueTessellatingHeckler
Thanks. That worked. It does require the quotes however, which I think is what I missed when I initially tried that.PGHE

1 Answers

1
votes

This should do it (you shouldn't need to use the subexpression $() operator unless you're accessing the property of a variable from within a string):

Import-CSV .\NameA.csv | ForEach-Object {Invoke-Sqlcmd `
  -Database $database -ServerInstance $server `
  -Query "insert into $table VALUES ('$($_.Feature1)','$($_.Feature2)', '$NameValue')"
}