Search code examples
powershellactive-directoryparameter-splatting

Sorting properties with PowerShell splatting


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?


Solution

  • 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)
        }
    }