Group unique filenames by expression?

Posted on 2010-11-10
Last Modified: 2012-08-13
I have a directory full of unique names, all in the same format - Scriptname_datecodestuff.txt
How can I group these based on 'scriptname' ?
What I need to accomplish is I only want to have 10 'versions' of a file in this directory, so if their are more than 10, I need to delete the oldest of that group

Example files in the dir

With those listtings, the 2 groups would be localhost with a count of 3, and otherhost with a count of 3.

I have something semi working, but its not elogant, and suffers some bad performance..
$Group =$File.Name.SubString(0,(($File.Name.Length)-20))
ElseIf (($Directory | Where {$_.Name -Match $Group} | %{$_.Name.SubString(0,(($_.Name.Length)-20))} | Group | %{$_.count}) -gt 10) {
		$Directory | Where {$_.Name -Match $Group} | Sort -Property LastWriteTime | Select -First 1 | Remove-Item

Open in new window

Question by:rwskas

Author Comment

ID: 34103817
Sorry, that attached code was taken out of the entire script to just show the pieces that are relevant, the 2 lines dont flow together.
$file is a gci object
$directory = gci c:\temp
LVL 13

Accepted Solution

soostibi earned 500 total points
ID: 34107118
Try this:

Get-ChildItem C:\temp | foreach-object {
    Add-Member -InputObject $_ -MemberType noteproperty -Name Groupname -Value $(if($ -match "^[^_]*"){$matches[0]}else{$null}) -PassThru} | ?{$_.groupname} |
        Group-Object -Property groupname | ?{$_.count -gt 10} | foreach-object {
            $ | Sort-Object -Property lastwritetime | Select-Object -First 1 | Remove-Item

Open in new window


Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
Set OWA language and time zone in Exchange for individuals, all users or per database.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question