如何以与格式列表相同的顺序获取 powershell 对象属性? [英] How to get powershell object properties in the same order that format-list does?

查看:71
本文介绍了如何以与格式列表相同的顺序获取 powershell 对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Powershell 中编写一些报告脚本,并将项目汇总表收集为一个空白对象,并逐一添加其他属性:

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;

}

如果我在最后转储 $cmClusters,我会得到一个格式列表输出,其中的属性按照我添加的顺序排列.

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.

但是,我希望编写一个通用的将此对象集合转储到 Excel 选项卡"函数来生成我的报告,这将是来自不同对象列表的几个类似的工作表选项卡.

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.

看起来像这样:

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.

我可以使用什么来以与 Format-List 相同的顺序获取我的属性列表?

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

推荐答案

试试这个:

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

这篇关于如何以与格式列表相同的顺序获取 powershell 对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆