【问题标题】:How to get powershell object properties in the same order that format-list does?如何以与格式列表相同的顺序获取 powershell 对象属性?
【发布时间】:2014-12-08 23:49:45
【问题描述】:

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

$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,我会得到一个格式列表输出,其中包含按我添加它们的顺序排列的属性。

但是,我希望编写一个通用的“将此对象集合转储到 excel 选项卡”功能来生成我的报告,这将是来自不同对象列表的几个类似的工作表选项卡。

看起来像这样:

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
}

可行,但属性名称现在按字母顺序排列。

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

【问题讨论】:

    标签: powershell


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 啊哈!完美的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多