1

I have powershell that reads from a database and successfully outputs. Problem is, when I insert commas, the program ignores it so when I open .csv file, all the data is in one column instead of five columns. How to fix this?

$count=0
do{
    try{
        $rdr = $cmd.ExecuteReader()


        while ($rdr.read()){
            $sql_output += ,@($rdr.GetValue(0), ",", $rdr.GetValue(1), ",", $rdr.GetValue(2), ",", $rdr.GetValue(3), ",", $rdr.GetValue(4))
            $count=$count + 1
        }
        $transactionComplete = $true
    }
    catch{
        $transactionComplete = $false
    }
}until ($transactionComplete)

$conn.Close()

foreach ($k in $sql_output){
     Add-Content D:\Script\Network_Threat_Protection.csv "$k" 
}

2 Answers 2

3

I would suggest creating an array of objects instead of an array of strings, and then you can just use Export-CSV. It would go something like:

    $sql_output = @()
    while ($rdr.read()){
        $sql_output += [PSCustomObject][Ordered]@{
            Col1=$rdr.GetValue(0)
            Col2=$rdr.GetValue(1)
            Col3=$rdr.GetValue(2)
            Col4=$rdr.GetValue(3)
            Col5=$rdr.GetValue(4)
        }
        $count=$count + 1
    }

Then for output:

$sql_output | Export-CSV "D:\Script\Network_Threat_Protection.csv" -NoTypeInfo -Append
Sign up to request clarification or add additional context in comments.

Comments

1
 $sql_output += @($rdr.GetValue(0)+ """,""" +$rdr.GetValue(1)+ """,""" +$rdr.GetValue(2)+ """,""" +$rdr.GetValue(3)+ """,""" +$rdr.GetValue(4)) 

1 Comment

when I open the file it says error, and it's still not separated into different columns

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.