Question

I use ConvertTo-HTML to convert a list of objects into a table. The only problem is that I cannot define the order of the columns in that table. I want a specific property (hostname) for all of the objects to be the first column in the table. Is there any way to do this?

Example Code:

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"
Was it helpful?

Solution

Here is one solution that modifies the function to create the object from an ordered hash table so that the order is maintained. This requires V3 or better.

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's another solution using Select-Object in the main script to reorder the properties before it's converted. This will work on V2 or better:

$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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top