Skip to content

# milestone patch v3.0.1 - a2 #9

Description

@aj1126

milestone patch v3.0.1 - a2

2. Duplicate Resolution Sorting Failure

File: src/MyBookTools.psm1

Function: Resolve-MyBookDuplicates

Issue: Duplicates are deleted at random rather than keeping the most recently modified file.

Root Cause: Get-FileHash strips the original FileInfo object, returning only Algorithm, Hash, and Path. Because LastWriteTime no longer exists in the pipeline, Sort-Object LastWriteTime -Descending fails silently.

Resolution:
Map the hashed paths back to full FileInfo objects using Get-Item -LiteralPath before applying the sort.

    $hashGroups = $files | Get-FileHash | Group-Object Hash | Where-Object Count -gt 1

    foreach ($group in $hashGroups) {
        # Map back to FileInfo objects to retrieve LastWriteTime
        $duplicateFiles = $group.Group | ForEach-Object { Get-Item -LiteralPath $_.Path }
        $sorted = $duplicateFiles | Sort-Object LastWriteTime -Descending
        
        $keep   = $sorted[0]
        $remove = $sorted[1..($sorted.Count - 1)]

        Write-MyBookLog -Message "Keeping newest duplicate: $($keep.FullName)"

        foreach ($f in $remove) {
            if ($DryRun) {
                Write-MyBookLog -Message "[DryRun] Would delete: $($f.FullName)"
            } else {
                if ($PSCmdlet.ShouldProcess($f.FullName, "Delete duplicate")) {
                    Remove-Item -LiteralPath $f.FullName -Force
                    Write-MyBookLog -Message "Deleted duplicate: $($f.FullName)"
                }
            }
        }
    }

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions