Formatting powershell SQL Server output into columns and rows

后端 未结 2 352
不思量自难忘°
不思量自难忘° 2021-01-27 14:44

I\'m a beginner with Powershell trying to query a SQL Server database and output the csv in a file organised rows and columns. I can partially achieve this with the following co

2条回答
  •  故里飘歌
    2021-01-27 15:10

    Export-Csv expects the input to be objects. String input is considered as string objects, which have just one property (Length), so only this property is exported. If your input is an array of strings, you need to make it into an object, e.g. like this:

    $array = "foo", "bar", "baz"
    
    New-Object -Type PSCustomObject -Property @{
      "a" = $array[0]
      "b" = $array[1]
      "c" = $array[2]
    } | Export-Csv output.csv -NoTypeInformation
    

    The above would create a file output.csv with the following content:

    "c","a","b"
    "baz","foo","bar"
    

    The property names (a, b, c) are become the CSV headers, the property values (foo, bar, baz) become the CSV values.

    If your SQL query generates a list of arrays, you'll probably have to do something like this:

    Invoke-Sqlcmd ... | % {
      New-Object -Type PSCustomObject -Property @{
        "col1" = $_[0]
        "col2" = $_[1]
        "col3" = $_[2]
      }
    } | Export-Csv output.csv -NoTypeInformation
    

    I don't have an SQL server at hand, though, so take with a grain of salt.

提交回复
热议问题