我使用System.Data.SqlClient从SQL中提取数据,并最终将数据集存储到变量中:
$SqlQuery = "select * from my_Table"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$amManagedFolders = New-Object System.Data.DataSet
$SqlAdapter.Fill($dataset)
然后,我通过类型为$dataset.Tables[0]
System.ComponentModel.MarshalByValueComponent
访问该表格
我需要能够使用ForEach
来遍历该表并将结果存储到CustomPSObject
中供以后使用,但是,我不确定要按顺序使用的方法为达到这个。
答案 0 :(得分:0)
使用this page我发现以下代码很有帮助。我正在进行SQL查询并生成带有结果的Excel工作簿。
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSetTable = $DataSet.Tables["Table"]
## - Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName
## - Build column header:
[Int] $RowHeader = 1
foreach ($ColH in $getColumnNames)
....
foreach ($rec in $DataSetTable.Rows)
{
foreach ($Coln in $getColumnNames)
{
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@"
## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
$ColData++
}
$rowData++; $ColData = 1
}
-Edit,看到你的评论。您可以将the answer改为此问题