Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use powershell to copy files into subfolders based on whether or not the file size is unique?

Tags:

powershell

I have a folder full of .wav files that I'd like to copy into subfolders called "Unique Size" and "Non-Unique Size". Around half of the files are the same size down to the byte:

Get-ChildItem "*.wav" | Group-Object -Property Length -NoElement | Sort-Object Count -Descending

Count Name     Group (Example)
----- ----     ----
    6 26244078 {file206.wav, file137.wav, file 101.wav, etc.}
    5 28716602
    5 28807758
    5 30750266
    ...
    1 17773794 {file31.wav}
    1 18144078
    1 18432082
    1 70589446

I'd like them to be copied into "Unique Size" if Group Count = 1 and "Non-Unique Size" otherwise, but I'm fairly inexperienced with powershell and CLI in general and I'm not really sure what to do with the output of the command at this point. I have tried a few searches online but my keywords don't seem to be getting me anywhere for this rather unique problem. Any help is appreciated, thank you!

like image 683
Enceladus Avatar asked Nov 17 '25 07:11

Enceladus


1 Answers

What you need is to loop over the groups and depending on their .Count property copy the files to either the Unique Size or the Non-Unique Size folders.

$sourcePath    = 'X:\path\to\all\wav\files'
$uniquePath    = 'X:\path\to\Unique Size'
$differentPath = 'X:\path\to\Non-Unique Size'

Get-ChildItem -Path $sourcePath -Filter '*.wav' -File | Group-Object -Property Length | ForEach-Object {
    $destination = if ($_.Count -gt 1) {$differentPath} else {$uniquePath}
    foreach ($file in $_.Group) {
        $file | Copy-Item -Destination $destination
    }
}
like image 173
Theo Avatar answered Nov 19 '25 20:11

Theo