簡體   English   中英

新對象返回空對象

[英]New-Object returns empty object

我正在嘗試使用外部模塊擴展該示例以調用通用方法。 我的目標是創建新的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類(基類DocumentFormat.OpenXml.Spreadsheet.Sheets )實現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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM