Sorting properties with PowerShell splatting

629 Views Asked by At

I am using Active Directory module for Windows PowerShell to export certain values from Active Directory. How can I display the results in the same order as the properties are listed? When I run this command I get all of the properties available listed in alphabetical order. But what I want and expect is to get only the properties I have listed in the hashtable in the same order as the hash table.

$GetADUserOptions = @{
    properties = @(
    "employeeID",
    "employeeNumber",
    "whencreated",
    "wWWHomePage",
    "c",
    "CO"
    )
}
Get-ADUser @GetADUserOptions

What am I missing?

2

There are 2 best solutions below

1
On BEST ANSWER

You can't control the order the properties are returned to you by Active Directory or the module.

But if what you're doing with the resulting data is exporting to something like CSV (or even just the console) and you care about the order of the columns, just use Select-Object with your desired order before doing the export.

You can just pass the array from the splat as @AdminOfThings suggested like this

Get-ADUser @GetADUserOptions | Select-Object $GetADUserOptions.properties

Or you can do it explicitly which also allows for some post-processing of attributes that aren't very human-readable by default like lastLogonTimestamp or pwdLastSet.

# assuming lastLogonTimestamp was added to your list of properties
Get-ADUser @GetADUserOptions | Select-Object sAMAccountName,@{
    Label='LastLogonTS'
    Expression={
        [DateTime]::FromFiletime($_.lastLogonTimestamp)
    }
}
0
On

Using the [ORDERED] syntax will force the array to return the order of the results.

 $GetADUserPropertiesEAD = [ORDERED]@{
    'Properties' =  'Name',
                    'GivenName',
                    'Surname',
                    'Description',
                    'Enabled',
                    'LastLogonDate',
                    'ObjectClass',
                    'ObjectGUID',
                    'SamAccountName',
                    'SID',
                    'UserPrincipalName',
                    'DistinguishedName',
                    'extensionattribute5'

    } #end $GetADUserProperties

get-aduser -Filter {enabled -eq $False} @GetADUserPropertiesEAD | select $GetADUserPropertiesEAD.Properties