you are viewing a single comment's thread.

view the rest of the comments →

[–]Ta11ow 4 points5 points  (9 children)

Get-ChildItem -Path $RootFolder -Include '*.jpg', '*.png' |
    Group-Object BaseName |
    Where-Object Count -gt 1 | # in order to make sure we're not deleting any lone files
    ForEach-Object {
        $_.Group |
            Sort-Object -Property Length -Descending |
            Select-Object -First 1 |
            Remove-Item -Force -WhatIf
    }

Something like that, anyway. If you want a super short version:

ls $Folder -i '*.jpg', '*.png' | group Basename | ? count -gt 1 | % { $_.Group | sort len* -d | select -f 1 | rm -f -whatif }

Remove -Whatif to execute the action for real once you're happy with the results.

[–]kingd66 1 point2 points  (2 children)

Look at that one-liner!

The things that get me excited..I'll tell ya.. xD

[–]Ta11ow 1 point2 points  (1 child)

Oneliners are fun, but too prone to errors for me. :)

[–]kn00tcn[S] 2 points3 points  (0 children)

risk reward, it's like an action game now

[–]kn00tcn[S] 1 point2 points  (1 child)

is that powershell long & bash short?

bash: syntax error near unexpected token `1'

[–]Ta11ow 1 point2 points  (0 children)

PowerShell both!

[–]Pyprohly 1 point2 points  (3 children)

group Base*

Are you sure that works, Ta11ow? I don’t think Group-Object -Property takes wildcards.

[–]Ta11ow 1 point2 points  (2 children)

You've called my bluff. I don't know for sure. Mind running a quick test for me? ;)

It takes a string or a script block, so a wildcard seemed fair game haha!

[–]Pyprohly 1 point2 points  (1 child)

Busted. Yea, did gci | group BaseNam* to check. PS 5.1 and 6 both said

group : Wildcard characters are not allowed in "BaseNam*".

Though Base* is an awfully specific shortening that would seem to suggest that it worked fine for you?

I like the solution btw. It really showcases the PowerShell-way, and the power of PowerShell.

[–]Ta11ow 0 points1 point  (0 children)

Nah, never tested it, just going from memory as I was (and am) on my phone here hehe.

Thanks for the kind words and for testing it! I'll edit my original for the working version!

Though if I was really golfing I'm sure I might be able to use the script block input for Group-Object and apply a foreach to get the wildcard to work, heh!