将对象传递给 PowerShell 函数

Passing objects to PowerShell functions

我正在尝试将 SQL 适配器对象传递给 PowerShell 函数,但出现此错误:

executeQueryAndFillTable : Cannot process argument transformation on parameter 'da'. Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Data.SqlClient.SqlDataAdapter".

这是代码

function sql_pull
{
    # define Objects
    $xmlDoc = New-Object System.Xml.XmlDocument
    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
    $sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $connectionString = "Password=$password;Persist Security Info=True;User ID=$userId;Data Source=$dataSource"
    $counter = 0

    # database queries 
    $queries = @(
    "Select * from sys.configurations for xml Raw ('Cretiria'), type, ROOT('sys.configurations'), ELEMENTS");

    $sqlConnection.ConnectionString = $connectionString
    $sqlCommand.Connection = $sqlConnection

    try {
        $sqlConnection.Open()
        
        foreach($q in $queries) 
        {
            $sqlCommand.CommandText = $q
            $sqlAdapter.SelectCommand = $sqlCommand.CommandText
            $sqlAdapter.SelectCommand.CommandTimeout = 300

            $res = executeQueryAndFillTable($sqlAdapter, $sqlCommand)              
        }

        $sqlConnection.Dispose()
        $sqlCommand.Dispose()
        $sqlAdapter.Dispose()
    } 
    catch
    {
        Throw
    }    
}

function executeQueryAndFillTable
{
    param(
        [System.Data.SqlClient.SqlDataAdapter]$da,
        [System.Data.SqlClient.SqlCommand] $command
    )

    $dataTable = New-Object System.Data.DataTable
    $da.SelectCommand = $command
    $da.Fill($dataTable)
    #check
    $data = $dataTable.Rows[0][0]
    return $data
}

两件事:

首先 : 在PowerShell函数中应该在使用前声明。

其次:函数的调用方式

executeQueryAndFillTable($sqlAdapter, $sqlCommand)

这不是在 PowerShell 中调用函数的正确方法。如果你这样调用它,PowerShell 认为你调用的函数只有一个参数,它是一个数组(非常重要 , 是 PowerShell 中的数组运算符),具有两个不同类型的元素([=13= 的原因) ] 在错误中)。

正确的方法是:

executeQueryAndFillTable $sqlAdapter $sqlCommand