在Powershell中使用ConvertTo-HTML时,如何在HTML输出中订购列?

时间:2014-04-05 00:02:21

标签: html sorting powershell powershell-v2.0 powershell-v3.0

我使用ConvertTo-HTML将对象列表转换为表格。唯一的问题是我无法定义该表中列的顺序。我希望所有对象的特定属性(主机名)成为表中的第一列。有没有办法做到这一点?

示例代码:

function Create-MyObject {
    param(
        $name
    )

    $object = New-Object -TypeName PSObject -Property @{
        "Name" = $name
        "Prop1" = Get-Property1 $name
        "Prop2" = Get-Property2 $name
        "Prop3" = Get-Property3 $name
    }

    return $object
}

$myarray = @()

foreach($value in $list)
{
    $myarray += Create-MyObject -name $value
}

Add-Content -Value $(ConvertTo-HTML $myarray | Out-String) -Path "C:\Temp\output.html"

1 个答案:

答案 0 :(得分:1)

这是一个解决方案,它修改函数以从有序散列表创建对象,以便维护订单。这需要V3或更高版本。

function Create-MyObject {
    param(
        $name
    )

    $object = New-Object -TypeName PSObject -Property [ordered]@{
        "Name" = $name
        "Prop1" = Get-Property1 $name
        "Prop2" = Get-Property2 $name
        "Prop3" = Get-Property3 $name
    }

    return $object
}

 $myarray = @()

    foreach($value in $list)
    {
        $myarray += Create-MyObject -name $value
    }

Add-Content -Value $(ConvertTo-HTML $myarray | Out-String) -Path "C:\Temp\output.html"

Heres的另一个解决方案是在主脚本中使用Select-Object在转换之前对属性进行重新排序。这将适用于V2或更好:

$myarray = @()

foreach($value in $list)
{
    $myarray += Create-MyObject -name $value
}

Add-Content -Value $(ConvertTo-HTML $myarray | Out-String) -Path "C:\Temp\output.html"



function Create-MyObject {
    param(
        $name
    )

    $object = New-Object -TypeName PSObject -Property @{
        "Name" = $name
        "Prop1" = Get-Property1 $name
        "Prop2" = Get-Property2 $name
        "Prop3" = Get-Property3 $name
    }

    return $object
}

$myarray = @()

foreach($value in $list)
{
    $myarray += Create-MyObject -name $value
}

$myarray = $myarray | select Name,Prop1,Prop2,Prop3

Add-Content -Value $(ConvertTo-HTML $myarray | Out-String) -Path "C:\Temp\output.html"