我写了一个函数,它从一个数组创建一个XLS文件。一切正常,但我从阵列中提取标题时遇到问题。
我的标题在提取后按字母顺序排列,但我希望它们与我的输入数组保持相同的顺序。
function DoTheMagicExcel {
[cmdletbinding()]
Param(
<# Array to work on #>
[Parameter( Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Array]$MyArray,
<# Its Excel Sheet name #>
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[alias('Sheet')]
[string]$MySheetName,
<# Excel file name #>
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidatePattern("\.(csv|xls)$")]
[alias('XlsFile')]
[string]$MyExcelFile
)
Begin {
<# Init them all #>
$excel = new-object -comobject Excel.Application
$excel.visible = $False
$excel.DisplayAlerts = $False
$XlsAlreadyExist = $False
if (Test-Path $MyExcelFile) {
Write-Output "Fichier Excel deja existant"
$XlsAlreadyExist = $true
$workbook = $excel.Workbooks.open("$PSScriptRoot\$MyExcelFile")
$workbook.Worksheets.Add() | Out-Null
$workbook.WorkSheets.item(1).Name = $MySheetName
$MySheet = $workbook.Worksheets.Item($MySheetName)
}
else {
$workbook = $excel.Workbooks.Add()
$workbook.WorkSheets.item(1).Name = $MySheetName
$MySheet = $workbook.Worksheets.Item($MySheetName)
}
$MyHeadercolumn = 1
$StartRow = 2
}
Process {
$MyArrayHeader = $MyArray | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'
foreach ($header in $MyArrayHeader) {
$MySheet.cells.item(1, $MyHeadercolumn).font.bold = $true
$MySheet.cells.item(1, $MyHeadercolumn) = $header
$MyHeadercolumn++
}
foreach ($ThisRow in $MyArray) { ......
我的意思是
$AllBcksummary[1] |ft -AutoSize
Server RG Environment Availibility Vault Status Regle Dernier Backup Type
------- -- ----------- ------------ ------ ------ ----- -------------- ----
SEFRAPB0106 RG_AXL production NOT SET backup Healthy Policy14512-BDay-Prod 24/01/2018 19:22:15 AppConsistent
$MyArrayHeader = $AllBcksummary | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'
$MyArrayHeader |ft -AutoSize
Availibility
Coffre
Dernier Backup
Environment
Regle
RG
Serveur
Status
Type
然后,当我创建我的Excel时,我不再保留其原始订单
foreach ($header in $MyArrayHeader) {
$MySheet.cells.item(1, $MyHeadercolumn).font.bold = $true
$MySheet.cells.item(1, $MyHeadercolumn) = $header
$MyHeadercolumn++
}
如果你有个主意...... :) 感谢
答案 0 :(得分:0)
这应该可以解决问题:)
$AllBcksummary.psobject.properties | select Name
来自How to get powershell object properties in the same order that format-list does?;)
答案 1 :(得分:0)
几乎:)
$AllBcksummary.psobject.properties | select name
Name
----
Capacity
Count
IsFixedSize
IsReadOnly
IsSynchronized
SyncRoot
但添加索引0可以解决问题!
$AllBcksummary[0].psobject.properties | select name
Name
----
Serveur
RG
Environment
Availibility
Coffre
Status
Regle
Dernier Backup
Type
谢谢你们