GetEnumerator - random order

Hi,

I have a hashtable that contains a set of values, based on some AD properties.

$SelectedADUser = Get-aduser -Identity "user01" -Properties *
$Data = @{
    'First and middle name' = $SelectedADUser.givenname
    'Last Name'             = $SelectedADUser.Surname
    Username                = $SelectedADUser.SamAccountName
    Title                   = $SelectedADUser.Title
    Mobile                  = $SelectedADUser.mobile
    Office                  = $SelectedADUser.Office
    Manager                 = $SelectedADUser.Manager
    Location                = $SelectedADUser.extensionAttribute1
    Department              = $SelectedADUser.extensionAttribute11
    'SAP ID'                = $SelectedADUser.EmployeeNumber
}.GetEnumerator() | 
    Sort-Object Key -Descending | 
    ForEach-object {
        [PSCUstomObject]@{ 
            Name  = $_.Name; 
            Value = $_.Value 
        } 
    }
$data

The data is present, and i can use it in my code - but i would like the Key value it to be arranged in the same order, as it is in the Hashtable. So that its “First and middle name” first… This is how it looks now:
image

How do i achieve this?

You can specify the type as [Ordered]:

$Data = [Ordered]@{
    'First and middle name' = $SelectedADUser.givenname
    'Last Name'             = $SelectedADUser.Surname
    Username                = $SelectedADUser.SamAccountName
}

That syntax breaks GetEnumerator() though, so if you really need to do that, you’ll have to use:

$Data.GetEnumerator()

You’re changing the (displayed) order anyway with Sort-Object, is that intentional?

1 Like

I need to use the .GetEnumerator(), but your example did the trick! Thanks a lot :slight_smile: