Search code examples
powershellgrouping

How to group all Files in folder that have same six digit number in their file name in Powershell?


I am trying to come up with a script that looks at a folder and then copies all files that have the same timestamp in their file name together into another folder but I'm struggling with the grouping part already.

the file names look something like this (number to group by in bold):

mork-work03_lork1360-D-000_20230925_142604_kok.txt
mork-work03_lork1360-D-000_20230925_142604_kok.dat
mork-work03_lork1360-D-000_20230925_142634_kok.exe
mork-work03_lork1360-D-000_20230925_142634_kok.txt
mork-work03_lork1360-D-000_20230925_142634_kok.dat

So they should be grouped and copied like

mork-work03_lork1360-D-000_20230925_142604_kok.exe
mork-work03_lork1360-D-000_20230925_142604_kok.txt
mork-work03_lork1360-D-000_20230925_142604_kok.dat

mork-work03_lork1360-D-000_20230925_142634_kok.exe
mork-work03_lork1360-D-000_20230925_142634_kok.txt
mork-work03_lork1360-D-000_20230925_142634_kok.dat

For this I tried to group them using regex but I only manage to group them if they contain a 6 digit number and not if they have identical ones in their name. I also thought about using the Index inside the filename but the timestamp is not necessarily always in the same position in the name. Can somebody help ? this is my first time using ps

$GroupedFiles = Get-ChildItem $SourcePath | 
    Group-Object {($\_ | Get-Item).BaseName -match '\d{6}'}

this is my latest attempt


Solution

  • I'd use the structure you have in your filenames to split them into pieces and then re-join the desired pieces together to group the files as wanted ... like this:

    $GroupedFiles = 
        Get-ChildItem $SourcePath | 
            Group-Object {
                ($_.BaseName -split '_')[2..3] -join '_'
            }