powershellfilegroupingversion

Group files whose names have embedded version numbers and process all but the latest versions


Preface:


I have a large set of files whose names contain version numbers; e.g.:

FileBam-0.10.1.zip
FileBam-0.2.0.zip
FileBoozle-1.7.2.zip
FileBoozle-1.7.5.zip
FileBoozle-1.7.10.zip
FileWam-0.97.40.zip
OtherFile-5.5.zip

Using PowerShell, I'd like to:


Solution

  • Use the following:

    Get-ChildItem -Filter *.zip | 
      Group-Object -Property { ($_.BaseName -split '-')[0] } |
      Where-Object Count -gt 1 |
      ForEach-Object {
        $_.Group | 
          Sort-Object -Descending -Property { [version] ($_.BaseName -split '-')[-1] } |
          Select-Object -Skip 1
      } |
      Remove-Item -WhatIf
    

    Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want.