本文介绍了将对象传递给 PowerShell 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass a SQL adapter object to a PowerShell function but I'm getting this error:

executeQueryAndFillTable:无法处理参数转换参数'da'.无法转换System.Object[]"类型值System.Object[]"键入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中函数应该在使用前声明.

First : In PowerShell function should be declare before usage.

第二:函数的调用方式.

executeQueryAndFillTable($sqlAdapter, $sqlCommand)

这不是在 PowerShell 中调用函数的正确方法.如果您以这种方式调用它,PowerShell 会认为您调用的函数只有一个参数,该参数是两个不同类型元素的数组(非常重要的 是 PowerShell 中的数组运算符)(为什么 System.Object[] 在错误中).

This is not the right way to call a function in PowerShell. If you call it this way PowerShell thinks you are calling the function with only one parameter which is an array (very important , is the array operator in PowerShell) of two elements of distinct types (the reason why System.Object[] in the error).

正确的做法是:

executeQueryAndFillTable $sqlAdapter $sqlCommand

这篇关于将对象传递给 PowerShell 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 02:29
查看更多