Sorting Get-ADuser results by PasswordLastSet date.

Hi Everyone, I am very new to using Powershell and looking for some assistance in sorting the results of my query of AD Users. Here is what I have so far. I was able to get the results that I wanted, except wish it to be sorted by PasswordLastSet date, oldest to newest. I think it probably needs to happen outside the for loop, but not quite sure how to get there.

$userfile = “C:\test_account_list.txt”

ForEach ($user in ( Get-Content $userfile)) {
$aduser = Get-ADUser -Identity $user -Properties * | Select Name, PasswordLastSet
$aduser
}

 

 

Take a look at Sort-Object:

Thank you for your response Rob. In my script, I have a for loop, where the results of the AD query is stored in a variable. Since I have several accounts listed in the input file, the query is ran once for each account. I would like to sort all of the results that are captured. I don’t see any cmdlet that would append the results of all the queries into a single variable. If I were to add a sort to my existing query, then it is only sorting 1 result, which would not be to useful. Any suggestions on how to get all the information together so that I can then pass it to sort?

Assigning a collection (array) to a variable in PS, couldn’t be simpler. With your example it would look like this:

$userarray = ForEach ($user in ( Get-Content $userfile)) {
    $aduser = Get-ADUser -Identity $user -Properties * | Select Name, PasswordLastSet
    $aduser
}

From there you can access $userarray and pipe it to whatever you want.

$userarray | Sort-Object -Property PasswordLastSet

 

Thank you Mike! This worked great!