传递给Function时,OleDbConnection变为System.Object

我有一个使用OLEDB从Excel文件读取PowerShell脚本。 我做了一个函数,它build立了基于一些参数的连接,工作得很好。 它创build了System.Data.OleDb.OleDbConnection连接,然后将其传递给其他函数以获取有关工作表(工作表名称,列名称)的其他信息。

直到我将连接对象传递给实际查询电子表格中的主工作表的函数时,这些函数都很好用。 在函数调用之前,我可以使用GetType()方法validation连接对象是否仍然是System.Data.OleDb.OleDbConnection对象。 在函数内部,它突然变成了一个System.Object[] ,在我的函数完成任何工作之前。

因此,当我尝试将连接分配给新的OleDbCommand对象时,我收到错误:

exception设置“连接”:“无法将”System.Object []“types的”System.Object []“值转换为键入”System.D ata.OleDb.OleDbConnection“。 在D:\ Scripts \ AdvancementSpreadsheetImport.ps1:130 char:18 + $命令。 <<<< Connection = $ connection + CategoryInfo:InvalidOperation:(:) [],RuntimeException + FullyQualifiedErrorId:PropertyAssignmentException

把function块外的代码放在脚本的主体中,一切正常。

任何想法是什么给?

创build连接:

 Function connectToSheet($sheetPath) { try { #Construct the data source $provider = "Provider=Microsoft.ACE.OLEDB.12.0" #Microsoft.Jet.OLEDB.4.0" $dataSource = "Data Source=`"$sheetPath`"" $extend = 'Extended Properties="Excel 12.0 Xml;HDR=YES;"' $connection = New-Object System.Data.OleDb.OleDbConnection("$provider;$dataSource;$extend;") $connection.Open() log("Connection to $sheetPath open") return $connection } catch {handleError("Error opening OLE connection to the spreadsheet $sheetPath.")} } 

有问题的function:

 Function constructIndexFile($connection, $sheetName, $outputPath, $outputFileName) { log("Connection info: $($connection.GetType())") #You can see that the connection object's type has changed at this point try { $query = "select [col1], [col2] from [$sheetName] where [col1] <> `"`"" $command = New-Object System.Data.OleDb.OleDbCommand($query) 

下一行触发错误。

  $command.Connection = $connection $DataReader = $command.ExecuteReader() $indexFileStream = [System.IO.StreamWriter] "$outputFileName" While ($DataReader.read()) { ##Do stuff to construct my index file } $indexFileStream.close() log("Created index file $outputFileName") } catch {handleError("Error constructing the index file")} } 

PowerShell不使用括号来调用函数; 而是在函数名称以空格分隔之后传递参数。 因此,而不是

 function_name(param[, ...]) 

 function_name param [...]