从 powershell 中的 sql 查询输出中删除列标题

从 powershell 中的 sql 查询输出中删除列标题

我想从 SQL Server 查询输出中删除列标题。我搜索过但没有找到任何解决方案。我有一个脚本。

$Database = "temp"
$Server = "localhost"

$AttachmentPath = "output.csv"


# Connect to SQL and query data, extract data to SQL Adapter

$SqlQuery = "select cc.DepartmentID , cc.Name  from HumanResources.Department cc"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$nRecs = $SqlAdapter.Fill($DataSet)
$nRecs | Out-Null

#Populate Hash Table

$objTable = $DataSet.Tables[0]

#Export Hash Table to CSV File

$objTable | Export-CSV $AttachmentPath

当我运行此查询时,我得到了如下的输出。

#TYPE System.Data.DataRow           
ID  Name
12  Document Control
1   Engineering
16  Executive
14  Facilities and Maintenance
10  Finance
9   Human Resources

我想从输出中删除 ID 和名称(列标题)。输出中没有列标题。

请指教。

答案1

假设您也不想要类型信息,您可以使用ConvertTo-csv(输出到管道),然后跳过前两行:

$objTable | ConvertTo-Csv | select -Skip 2 > $AttachmentPath

相关内容