New-Object返回空对象
我试图扩展这个例子使用extarnal模块来调用generics方法。 我的目标是创build新的xls文件并写入它。
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml") | Out-Null [Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Packaging") [Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Spreadsheet") [Reflection.Assembly]::LoadWithPartialName("OpenXmlPowerTools") Import-Module (join-path (Split-Path $MyInvocation.MyCommand.Path) "GenericMethods.psm1") $document = [DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]::Create("C:\Temp\text.xlsx", [DocumentFormat.OpenXml.SpreadsheetDocumentType]::Workbook) $workbookPart = $document.AddWorkbookPart(); $workbookPart.Workbook = New-Object -TypeName DocumentFormat.OpenXml.Spreadsheet.Workbook $worksheetPart = Invoke-GenericMethod -InputObject $workbookPart -MethodName AddNewPart -GenericType DocumentFormat.OpenXml.Packaging.WorksheetPart $sheetData = New-Object -TypeName DocumentFormat.OpenXml.Spreadsheet.SheetData $worksheetPart.Worksheet = New-Object -TypeName DocumentFormat.OpenXml.Spreadsheet.Worksheet -ArgumentList $sheetData [DocumentFormat.OpenXml.Spreadsheet.Sheets]$foo = New-Object -TypeName DocumentFormat.OpenXml.Spreadsheet.Sheets Invoke-GenericMethod -InputObject $document.WorkbookPart.Workbook -MethodName AppendChild -GenericType DocumentFormat.OpenXml.Spreadsheet.Sheets -ArgumentList $foo $document.Close()
问题是这段代码
[DocumentFormat.OpenXml.Spreadsheet.Sheets]$foo = New-Object -TypeName DocumentFormat.OpenXml.Spreadsheet.Sheets Invoke-GenericMethod -InputObject $document.WorkbookPart.Workbook -MethodName AppendChild -GenericType DocumentFormat.OpenXml.Spreadsheet.Sheets -ArgumentList $foo
抛出错误Invoke-GenericMethod : No matching method was found
。 抛出是因为New-Object
创build的东西被Invoke-GenericMethod
函数视为空数组。 所以模块正在寻找没有参数的通用方法。 注意第一次调用Invoke-GenericMethod
工作正常。
我应该如何Invoke-GenericMethod
带-ArgumentList
参数的Invoke-GenericMethod
?
您的代码的问题是DocumentFormat.OpenXml.OpenXmlElement
类( DocumentFormat.OpenXml.OpenXmlElement
基类)实现IEnumerable
接口。 这使得PowerShell将DocumentFormat.OpenXml.Spreadsheet.Sheets
任何实例解释为集合,而不是单个对象。
当你写的时候
$foo
PowerShell将枚举集合并显示子元素(确切地说,您将看到子元素,因为格式化cmdlet通常会执行另一个集合枚举)。 而且由于您刚刚创build了这个对象,它将是空的,什么都不会显示。
要真正显示$foo
对象本身,你需要像这样写:
,$foo | Format-Table -Expand CoreOnly
要么
,,$foo
事实上,PowerShell将DocumentFormat.OpenXml.Spreadsheet.Sheets
实例解释为集合,也会影响如何转换为[Object[]]
(types为-ArgumentList
参数)。 与单一元素数组一样(因为您想调用具有单个参数的方法)而不是单个元素数组),PowerShell从单个元素中创build数组。
要解决你的问题,你需要自己包装到单个元素数组中。 你可以用一元逗号操作符来做到这一点:
-ArgumentList (,$foo)