Power SQL使用Data.tables

时间:2017-02-03 09:43:58

标签: sql powershell datatable datatables datasource

您好我有以下代码

function Invoke-SQL {
    param(
        [string] $dataSource = ".\SKYPE",
        [string] $database = "LcsCDR",
        [string] $sqlCommand = "SELECT * From UsersView"
      )

    $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null

    $connection.Close()
    $dataSet.Tables

}

$results = Invoke-SQL 

Write-Host $results.Rows.Count

foreach ($row in $results.Rows)
{
Write-Host "value is : $($row[4])"

}

我所期望的是拉回UserView表的内容并循环通过它将它放到屏幕上。一切都很直接。

但我在输出中使用列索引。我怎样才能首先列出表的列标题。然后能够循环使用标题而不是索引号。

所以我希望最后一行看起来如下,其中" userid"它是列标题。

Write-Host "value is : $($row["UserID"])"
这可能吗?

3 个答案:

答案 0 :(得分:2)

你甚至不必循环!

$results | Select-Object "UserID"

变质剂:

$results | Select-Object "UserID" | ForEach-Object {
    $_
}

$results | ForEach-Object {
    $_."UserID"
}

$_有点类似于“this”

答案 1 :(得分:1)

我建议您使用关闭Receive-SqlQuerySqlConnection的通用SqlDataReader函数。您可以传入scriptblock来处理读者。

function Receive-SqlQuery
{
    Param
    (
        [string]$ConnectionString,
        [string]$SqlQuery,
        [scriptblock]$ResultProcessor
    )

    try 
    {
        $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString
        $sqlConnection.Open()

        try
        {
            $sqlCommand = New-Object System.Data.SqlClient.SqlCommand($SqlQuery, $sqlConnection)
            $reader = $sqlCommand.ExecuteReader()
            Invoke-Command $ResultProcessor -ArgumentList $reader
        }
        finally # cleanup reader
        {
            if ($reader)
            {
                $reader.Close()
            }
        }
    }
    finally
    {
        $sqlConnection.Close();
    }
}

使用列名访问列的用法示例:

 $readerCallback = {
        Param($reader)
        while ($reader.Read()) {
            Write-Host $reader['UserID']
        }    
    }

$retrieveUsers = 
@'
SELECT * From UsersView
'@

Receive-SqlQuery -ConnectionString "yourConnectionString" -SqlQuery $retrieveUsers -ResultProcessor $readerCallback

答案 2 :(得分:0)

哦对不起我看到我可以使用它们!我花了20分钟尝试它并盲目地尝试使用{}而不是[]。一个盲目的时刻。

foreach ($row in $results.Rows)
{
Write-Host "calue is : $($row["UserID"])"

}

write-host $results.Columns

是我追求的命令。