Powershell, invoke-sqlcmd, export-csv 多条结果显示数据失败

Powershell, invoke-sqlcmd, export-csv fails to show data if there is more than one result

我有以下代码从 SQL 数据库中获取数据并将其导出到 CSV 文件中:

#Server and Database names
$SQLServer = "Servername"
$DB = "DatabaseName"

#SQL Command
$FullScriptSQL="Select * from MyTable WHERE Column = 'TestData'"

#Invoke the command, rename the column headers and export to CSV file
$FullScriptCallLinked = Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DB -Query $FullScriptSQL | select-object @{ expression={$_.Column1};label='Column1 Name'},@{ expression={$_.Column2};label='Column2 Name'},@{ expression={$_.Column3}; label='Column3 Name' },@{ expression={$_.Column4} ; label='Column4 Name' }
Export-CSV -Path ".\ResultFile\FullScript.csv" -inputobject $FullScriptCallLinked -Append -NoTypeInformation

如果只有一个结果,这将非常有效。但是如果有多个结果,它会在csv文件中显示如下

我不知道为什么要这样做。显然是数据库参数数据或类似的东西。谷歌搜索了几天没有运气。请比我更聪明的人提供帮助?

想通了。我知道我很接近!

#Server and Database names
$SQLServer = "Servername"
$DB = "DatabaseName"

#SQL Command
$FullScriptSQL="Select * from MyTable WHERE Column = 'TestData'"

#Invoke the command, rename the column headers and export to CSV file
$FullScriptCallLinked = Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DB -Query $FullScriptSQL 

foreach($i in $FullScriptCallLinked){
  select-object @{ expression={$_.Column1};label='Column1 Name'},@{ expression={$_.Column2};label='Column2 Name'},@{ expression={$_.Column3}; label='Column3 Name' },@{ expression={$_.Column4} ; label='Column4 Name' }
  Export-CSV -Path ".\ResultFile\FullScript.csv" -inputobject $i -Append -NoTypeInformation
}

与其使用效率很低的 Select-Object 重命名列,不如在查询本身中为列指定别名:

$SQLServer = "Servername"
$DB = "DatabaseName"

$query = @'
SELECT Column1 AS "Column1 Name",
       Column2 AS "Column2 Name",
       Column3 AS "Column3 Name",
       Column4 AS "Column4 Name"
FROM MyTable
WHERE ColumnX = 'TestData'
'@

Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DB -Query $query |
Export-CSV -Path ".\ResultFile\FullScript.csv" -NoTypeInformation

此外,正如我的评论,你的问题代码很好,应该可以工作,唯一的问题是使用 -InputObject 而不是将结果传递给 Export-Csv:

$FullScriptCallLinked | Export-Csv -Path ".\ResultFile\FullScript.csv" -NoTypeInformation