How do I get the properties of a powershell object in the same order as in the list of formats?

I am writing several report scripts in Powershell and compiling a pivot table of elements as an empty object with additional properties added:

$cmClusters = @() foreach ($Cluster in Clusters) { $cmCluster = New-Object System.Object $cmCluster | Add-Member -type NoteProperty -Name VC -Value $strVC $cmCluster | Add-Member -type NoteProperty -Name Name -Value $Cluster.name # etc... $cmClusters += $cmCluster; 

}

If I simply reset $ cmClusters at the end of this, I get the output of the list of formats with the properties in the order in which I added them.

However, I was hoping to write a general β€œdump of this collection of objects to the excel tab” to create my report, which will contain several similar sheet tabs from different object lists.

It looks like this:

 function DumpToExcel($workbook, $tabTitle, $list) { $sheet = $workbook.worksheets.add() $sheet.Name = $tabTitle $col = 1 $row = 1 $fields = $list[0] | Get-Member -MemberType NoteProperty | Select-Object * Foreach ($field in $fields) { $sheet.cells.item($row,$col++) = $field.Name } $heading = $sheet.UsedRange $heading.Font.Bold = $True $row++ Foreach ($cmCluster in $list) { $col=1 Foreach ($field in $fields) { $sheet.cells.item($row,$col++) = $cmCluster.($field.Name) } $row++ } $sheet.UsedRange.EntireColumn.AutoFit() | Out-Null } 

but property names are now in alphabetical order.

What can I use to get a list of properties in the same order as Format-List?

+5
source share
1 answer

Try the following:

 $fields = $list[0].psobject.properties | select name 
+12
source

Source: https://habr.com/ru/post/1208591/


All Articles