使用powershell处理多个SQL结果集

时间:2017-07-13 18:42:30

标签: sql-server powershell

我有几个查询用于识别SQL数据库中的问题,但我尝试使用powershell脚本创建,我可以使用它来自动执行此操作。我遇到的麻烦是,当我调用我的SQL脚本时,有多个结果集,我的脚本似乎只捕获第一个集合。我想知道我需要做些什么才能循环完成所有结果。这是只有一些简单选择的代码

$dataSource = 'Server'
$database = "DB"
$sqlcommand = @"
Select TOP 1000 * from tblA;
Select TOP 1000 * from tblB
"@


Function Convert-Dataset
{
    Param
    (
        [Parameter(Mandatory=$true)]
        $dataset
    )

    Begin
    {
        $return=@()
        For($r = 0; $r -lt $dataset.tables[0].rows.Count; $r++)
        {
            $table= new-object psobject
            If($dataset.tables[0].columns.ColumnName.Count -le 1)
            {
                $colName = [String]$dataset.tables[0].columns.ColumnName
                If($dataset.tables[0].rows.Count -eq 1)
                {
                    $colValue = [string]$dataset.tables[0].rows.$colName
                }
                Else
                {
                    $colValue = [string]$dataset.tables[0].rows[$r].$colName
                }
                $table | Add-Member -memberType noteproperty -Name $colName -Value $colValue
            }
            Else{
                For($c = 0; $c -lt $dataset.tables[0].columns.ColumnName.Count; $c++)
                {
                    $colName = [String]$dataset.tables[0].columns.ColumnName[$c]
                    $colValue = [string]$dataset.tables[0].rows[$r][$c]
                    $table | Add-Member -memberType noteproperty -Name $colName -Value $colValue
                }
            }
            $return +=$table
        }
    }
    End
    {
        Return $return
    }
}

$connectionString = "Data Source=$dataSource; " +
        "Integrated Security=True; " +
        "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()
$return=Convert-Dataset -dataset $dataset
$return | Out-GridView

1 个答案:

答案 0 :(得分:4)

我想通了

$connectionString = "Data Source=$dataSource; " +
        "Integrated Security=True; " +
        "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()

ForEach($table in $dataset.Tables)
{
        $table |Out-GridView -PassThru
}