New-Object returns 空对象

New-Object returns empty object

我正在尝试扩展 this example using extarnal module 以调用通用方法。我的目标是创建新的 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 创建的内容被 Invoke-GenericMethod 函数视为空数组。所以模块正在寻找没有参数的通用方法。请注意,对 Invoke-GenericMethod 的第一次调用工作正常。

我应该如何使用 -ArgumentList 参数调用 Invoke-GenericMethod

您的代码的问题在于 DocumentFormat.OpenXml.OpenXmlElement class(DocumentFormat.OpenXml.Spreadsheet.Sheets 的基础 class)实现了 IEnumerable 接口。这使得 PowerShell 将 DocumentFormat.OpenXml.Spreadsheet.Sheets 的任何实例解释为集合,而不是单个对象。

当你只写

$foo

PowerShell 将枚举集合并改为显示子元素(准确地说,您会看到子元素的子元素,因为格式化 cmdlet 通常会执行另一个集合枚举)。由于您刚刚创建了这个对象,因此它将是空的,不会显示任何内容。

要真正显示$foo对象本身,需要这样写:

,$foo | Format-Table -Expand CoreOnly

,,$foo

事实上,PowerShell 将 DocumentFormat.OpenXml.Spreadsheet.Sheets 的实例解释为集合,也会影响到 [Object[]]-ArgumentList 参数的类型)的转换方式。 PowerShell 从集合的元素创建数组,而不是包装到单个元素数组(因为你想用单个参数调用方法),就像它发生在单个对象中一样。

要解决您的问题,您需要自己包装到单个元素数组中。您可以使用一元逗号运算符来做到这一点:

-ArgumentList (,$foo)