Reputation: 45
In my folder testtemp, I've got this files
PS C:\scripts\testtemp> Get-ChildItem | select name,lastwritetime
Name LastWriteTime
---- -------------
AABASSI.TMC049913.mapdrives.txt 27/02/2015 11:01:11
AABASSI.TMC049916.mapdrives.txt 02/03/2015 14:29:31
AABASSI.TMC050020.mapdrives.txt 26/11/2014 18:08:48
aabassi.TMS064845.mapdrives.txt 06/03/2015 14:14:50
aaboud.DLECLERCQPC.mapdrives.txt 03/04/2015 09:02:03
aaboud.FHP030221.mapdrives.txt 30/12/2014 15:05:04
aaboud.FHP045846.mapdrives.txt 18/11/2014 10:15:05
Aaccus.FHP047416.mapdrives.txt 25/07/2014 08:16:19
AADRIENVASSE.PHP049659.mapdrives.txt 02/10/2015 14:18:15
AADRIENVASSE.RBXXAMET10.mapdrives.txt 06/08/2015 10:33:33
aagostini.FHP047082.mapdrives.txt 05/03/2015 13:38:07
aagricole.PHP053341.mapdrives.txt 30/03/2015 15:09:03
aagricole.TMS064745.mapdrives.txt 25/03/2015 12:32:06
aaiad.PHP053346.mapdrives.txt 09/06/2015 09:18:58
aaissaoui.FHP029908.mapdrives.txt 28/08/2014 14:41:09
aaissaoui.FHP030685.mapdrives.txt 15/11/2014 18:27:55
aaissaoui.FHP048791.mapdrives.txt 12/09/2014 10:22:19
aaissaoui.FHP048963.mapdrives.txt 06/11/2014 09:55:00
I just want to get only the most recent file for each login (for exemple AABASSi is a login)
If I try sort-object lastwritetime -descending and sort-object -property name -unique, there is a problem because for exemple, AAISSAOUI 28/08/2014 14:41:09 is NOT the most recent file :
Get-ChildItem | select @{l="name";e={($_.name.split(".")[0]).ToUpper()}},lastwritetime | Sort-Object lastwritetime -Descending | Sort-Object -Property name -Unique
name LastWriteTime
---- -------------
AABASSI 26/11/2014 18:08:48
AABOUD 30/12/2014 15:05:04
AACCUS 25/07/2014 08:16:19
AADRIENVASSE 02/10/2015 14:18:15
AAGOSTINI 05/03/2015 13:38:07
AAGRICOLE 25/03/2015 12:32:06
AAIAD 09/06/2015 09:18:58
AAISSAOUI 28/08/2014 14:41:09
Is ther a simple solution for my problem ?
Upvotes: 0
Views: 710
Reputation: 7489
The reason you're having the issue with sorting is that you sort it by the property you actually want, and then you sort it again by a different property (Name). Instead, group the objects by the string before the ".", and select only the newest object from each group. @PetSerAl's method is great:
Get-ChildItem | Group-Object {$_.Name.Split(".")[0]} | % {
$_.Group | Sort-Object LastWriteTime -Descending | Select-Object -First 1
}
Upvotes: 3