How to get powershell object properties in the sam

2020-07-10 03:03发布

问题:

I'm writing some reporting scripts in Powershell and collecting up a summary table of items as a blank object with additional properties added one by one:

$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 just dump $cmClusters at the end of this, I get a format-list output with the properties in the order that I added them.

However, I was hoping to write a generic "dump this collection of objects to an excel tab" function to produce my report, which will be several similar worksheet tabs from different lists of objects.

That 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
}

which works, but the property names are now in alphabetical order.

What can I use to get my list of properties in the same order that Format-List does?

回答1:

Try this:

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


标签: powershell