作为parameter passing时,值为空

我正在从excel电子表格阅读大量格式的文本。 当我做下面的事情时,一切正常。

Function Read-From-Excel { Param( [string]$fileName, [string]$sheetName="Sheet1" ) $excelObject = New-Object -ComObject Excel.Application $excelObject.Visible = $FALSE $excelBook = $excelObject.Workbooks.Open($fileName) $excelSheet = $excelBook.Sheets.Item($sheetName) $intRowMax = ($excelSheet.UsedRange.Rows).count $col = 1 $row = 1 $headers= @() While ($TRUE) { $column = $excelSheet.cells.Item($row, $col).Text If ($column -eq "") { Break } $headers += $column $col ++ } $text = "" For ($row = 2; $row -le $intRowMax; $row++) { # Wrapped in another function starting here $cell = $excelSheet.cells.Item($row, 1).Text If ($cell.StartsWith("#")) { $text += "-- {0}`n" -f $cell.substring(1) } Else { $c1 = $cell $c2 = $excelSheet.cells.Item($row, 2).Text -creplace '\s+', '' $c3= $excelSheet.cells.Item($row, 3).Text -creplace '\s+', '' $c4 = $excelSheet.cells.Item($row, 4).Text $c5 = $excelSheet.cells.Item($row, 5).Text $text += Format-Row $c1 $c2 $c3 $c4 $c5 } # Until here } Write-Host $headers Write-Host $text $excelObject.quit() } 

当我包装一个函数的内部部分,但是,我得到的错误:

 You cannot call a method on a null-valued expression. At C:\Users\dannnno\desktop\FormatFromExcel.ps1:311 char:27 + $cell = $excelSheet.cells.Item <<<< ($row, 1).Text + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 

该function看起来像这样

 Function _Get-Next-Block-Excel-File { Param( [Object[]]$sheet, [int]$row ) # This is all the same, except with the name changed to $sheet } 

原来的代码有内部部分改为看起来像

 $text += _Get-Next-Block-Excel-File $excelSheet $row 

有什么特殊的方法,我必须在PowerShell中传递此参数?

你不需要一个Object[]数组作为Function _Get-Next-Block-Excel-File的第一个参数, [Object]$sheet会很好,因为你没有传递一个表单到这个函数。