Powershell - Get file size by similar name

Viewed 47

When I run "Get-ChildItem" PowerShell returns below

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2021-05-02   9:45 PM          47726 abc.123.Copy.2.pdf
-a----        2021-05-02   9:45 PM          47726 abc.123.Copy.3.pdf
-a----        2021-05-02   9:45 PM          47726 abc.123.Copy.4.pdf
-a----        2021-05-02   9:45 PM          47726 abc.123.Copy.6.pdf
-a----        2021-05-02   9:45 PM          47726 zxc.098.Copy.2.pdf
-a----        2021-05-02   9:45 PM          47726 zxc.098.Copy.3.pdf
-a----        2021-05-02   9:45 PM          47726 zxc.098.Copy.4.pdf
-a----        2021-05-02   9:45 PM          47726 zxc.098.Copy.5.pdf
-a----        2021-05-02   9:45 PM          47726 zxc.098.Copy.6.pdf
-a----        2021-05-02   9:45 PM          47756 poi.787.Copy.1.pdf

How can I find out how to get the amount of files and their total sizes based on the similar starting name to output something like below?

Total size of similar files:
abc = 190,904
zxc = 238,630
poi = 47756 


Total files:
abc = 4
zxc = 5
poi = 1
1 Answers

Assuming you want to group the files by the first token of the split string and they all follow this naming convention, you can use Group-Object to group them and then loop over them to get the desired output. I would advise you to output an object instead of a string since an object can be exported to CSV and be easily sorted / filtered.

The code to run would be similar to this:

Get-ChildItem /path/to/files -File | Group-Object { $_.Name.Split('.')[0] } | ForEach-Object {
    [pscustomobject]@{
        Count        = $_.Count
        StartingName = $_.Name
        TotalLength  = [System.Linq.Enumerable]::Sum([int64[]]$_.Group.Length)
    }
}

As for testing how the output would look, based on your sample data:

Count StartingName TotalLength
----- ------------ -----------
    4 abc               190904
    5 zxc               238630
    1 poi                47756
Related