3

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.

2
  • 1
    just $NameValue Commented Jul 10, 2017 at 23:52
  • Thanks. That worked. It does require the quotes however, which I think is what I missed when I initially tried that. Commented Jul 11, 2017 at 0:08

1 Answer 1

2

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')"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.