我有一個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
(注意,從System.Data.SqlClient.SqlDataReader
改變聲明的類型的$reader
參數來System.Data.Common.DbDataReader
沒有幫助。)
我是一個有經驗的開發人員,但新的.NET和很新的PowerShell的。