Home > Software engineering >  powershell find newest file based on 1st 2 chars
powershell find newest file based on 1st 2 chars

Time:12-09

I have files like this in folder:

C:\G1001
C:\G1002
C:\G2001
C:\G2002
C:\G2003
C:\1G001
C:\1G003
C:\1G025

How do I get the latest file based on 1st 2 chars of file name. I need output like this (using powershell):

C:\G1002
C:\G2003
C:\1G025

CodePudding user response:

You can combine Group-Object with Sort-Object:

  • Group the files by the first 2 chars of it's BaseName - Group-Object { -join $_.BaseName[0..1] }
Count Name  Group
----- ----  -----
    3 1G    {/path/to/folder/1G001.ext, /path/to/folder....
    2 G1    {/path/to/folder/G1001.ext, /path/to/folder....
    3 G2    {/path/to/folder/G2001.ext, /path/to/folder....
  • For each group, sort them -Descending (from highest to lowest) and get the first one with Select-Object -First 1
Get-ChildItem path/to/files | Group-Object { -join $_.BaseName[0..1] } |
ForEach-Object {
    $_.Group | Sort-Object BaseName -Descending | Select-Object -First 1
} 

Example

[System.IO.FileInfo[]]$files = @'
G1001.ext
G1002.ext
G2001.ext
G2002.ext
G2003.ext
1G001.ext
1G003.ext
1G025.ext
'@ -split '\r?\n'

$files | Group-Object { -join $_.BaseName[0..1] } |
ForEach-Object {
    $_.Group | Sort-Object BaseName -Descending |
    Select-Object FullName, Name -First 1
}

# Results in:

FullName                  Name
--------                  ----
/path/to/folder/1G025.ext 1G025.ext
/path/to/folder/G1002.ext G1002.ext
/path/to/folder/G2003.ext G2003.ext
  • Related