Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm converting a CSV to SQL inserts and there's a null-able text column which I need to quote in case it is not NULL. I would write something like the following for the conversion:

Import-Csv data.csv | foreach { "INSERT INTO TABLE_NAME (COL1,COL2) VALUES ($($_.COL1),$($_.COL2));" >> inserts.sql }

But I can't figure out how to add an additional tier into the pipeline to look if COL2 is not equal to 'NULL' and to quote it in such cases. How do I achieve such behavior?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

In the code block of the foreach-object cmdlet you can have multiple statements, something like:

Import-Csv data.csv | 
foreach {
  if ($_.COL1 -ne $null) {
    $c1 = "'$($_.COL1)'"
  } else {
    $c1 = $_.COL1
  }
  "INSERT INTO TABLE_NAME (COL1,COL2) VALUES ($c1,$($_.COL2));" >> inserts.sql
}
share|improve this answer
    
Thanks! This is a solution of course, but I wonder if there's a less verbose way of doing this, maybe something similar to how you can do filtering. –  axk Apr 16 '10 at 10:17
1  
PSCX () providers some helpers that work like a conditional operator which would certainly help in this case. pscx.codeplex.com –  Richard Apr 17 '10 at 8:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.