PowerShell - custom object - order of appearance in Out-GridView

1.4k Views Asked by At

A simple question but how to make it happen eludes me.

I created a new object so I can have custom columns in Out-GridView. My question is, in the code the order is DN, Role, Montage, Lieu ... but in the actual GridView, it appears as IP, Montage, Role, ...

How do I set the order of appearance so it fits with how to code is written?

*Using powershell v5.0

if ($user1)
    {
        $Object += New-Object PSObject -Property @{
            DN          = $OU;
            Role        = $role;
            Montage     = $datemontage;
            Lieu        = $lieu;
            IP          = $IPAddress;
            MAC         = $MACAddress3;
            Modèle1     = $modele1;
            Modèle2     = $modele2;
            Login       = $temps2;
            User        = $user2;
            InfoUser    = $info_user2;
        }


    }
    else
    {

        $Object += New-Object PSObject -Property @{
            DN     = $OU;
            Role     = $role;
            Montage  = $datemontage;
            Lieu     = $lieu;
            IP     = $IPAddress;
            MAC   = $MACAddress3;
            Modèle1  = $modele1;
            Modèle2  = $modele2;
            User    = "AUCUN";
        }



    }

enter image description here

2

There are 2 best solutions below

1
Janne Tuukkanen On BEST ANSWER

If you are creating the object from hashtable, in Powershell v3 and later you can use [ordered] type adapter:

$h = [ordered]@{B="First";A="Second"}
New-Object psobject -property $h
0
sabo-fx On

You can control the column order in Out-Gridview by piping the source output through select-object followed by the properties you need to be visible in order of appearance (in the grid view from left to right)

Example:

get-aduser 'JohnDoe' | select-object name,DistinguishedName | out-gridview

This results in a grid view with two columns 'Name' and 'DistinguishedName' (in that order).

enter image description here