无法从一个函数返回一个对象并将其传递给另一个函数

时间:2017-07-24 17:50:59

标签: powershell

我有一个Powershell函数,它调用存储过程并通过调用ExecuteReader结束。返回一个对象然后传递给另一个函数。在该过程中,对象的类型似乎在某处发生变化。我怀疑我在某个地方调用了一个方法而没有打算。

我已经将我的脚本修改为:

Param(
    [string] $DatabaseHost,
    [int32] $RunA,
    [int32] $RunB
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# This function works as expected.
Function New-DatabaseConnection {
    Param(
        [string] $databaseHost
    )
    $connectionProperties = @{}
    $connectionProperties.ConnectionString = "Server=$databaseHost;Database=fitbit;Integrated Security=True"
    $connection = New-Object -TypeName System.Data.SqlClient.SqlConnection -Property $connectionProperties
    $connection.Open()
    return $connection
}

Function Invoke-StoredProcedure {
    Param(
        [int32] $runA,
        [int32] $runB
    )
    $command = $connection.CreateCommand()
    $command.CommandType = [System.Data.CommandType] 'StoredProcedure'
    $command.CommandText = 'analysis.compareRunsWithSameInputs'
    [void] $command.Parameters.Add('@runA', $runA)
    [void] $command.Parameters.Add('@runB', $runB)
    return $command.ExecuteReader()  # What happens between here and the call to Write-ResultSetToSheet?
}

Function Write-ResultSetToSheet {
    Param(
        [System.Data.SqlClient.SqlDataReader] $reader
    )
    # The body of this function is irrelevant, because we don't get this far.
    [void] $reader.Read()
    Write-Output $reader.GetString(0)
}

$connection = New-DatabaseConnection $DatabaseHost
try {
    $reader = Invoke-StoredProcedure $RunA $RunB
    Write-ResultSetToSheet $reader  # This fails, because somehow the type of $reader has changed from SqlDataReader to DataRecordInternal.
} finally {
    $connection.Close()
}

当我执行此操作时,我收到此错误:

Write-ResultSetToSheet : Cannot process argument transformation on parameter 'reader'. Cannot convert the "System.Data.Common.DataRecordInternal" value of type "System.Data.Common.DataRecordInternal" to type "System.Data.SqlClient.SqlDataReader".
At C:\dev\ps1\Invoke-SoTest.ps1:45 char:28
+     Write-ResultSetToSheet $reader
+                            ~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Write-ResultSetToSheet], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Write-ResultSetToSheet

合并这两个函数虽然有效:

...
[void] $command.Parameters.Add('@runB', $runB)
$reader = $command.ExecuteReader()
Write-Output $reader.GetType()  # I'm using this to check the type of the object.  See below for more details.
[void] $reader.Read()
Write-Output $reader.GetString(0)

这是Write-Output $reader.GetType()的输出:

IsPublic IsSerial Name                                     BaseType                                                                                                                                                                                              
-------- -------- ----                                     --------                                                                                                                                                                                              
True     False    SqlDataReader                            System.Data.Common.DbDataReader

(请注意,将$reader参数的声明类型从System.Data.SqlClient.SqlDataReader更改为System.Data.Common.DbDataReader无效。)

我是一名经验丰富的开发人员,但他是.NET的新手,也是PowerShell的新手。

1 个答案:

答案 0 :(得分:6)

从函数返回时,Powershell有时会尝试展开对象。要强制Powershell不展开对象,请在返回的变量前面使用逗号return ,$myVar

这应该有助于在函数之间移动对象。如果Powershell很难确定对象类型,您可能还想确保强烈键入对象(例如,[int]$myInt = 7

另请参阅Powershell Operators了解更多信息。