我写了一个从数组中创建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 Availability 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
Availability
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++
}
2条答案
按热度按时间fkaflof61#
Almost:)
但是添加索引0就可以了!
谢谢你们
gajydyqb2#
这应该能起到作用:)
从How to get powershell object properties in the same order that format-list does?开始;)