PowerShell: Rename Files, to File Hash String

By Xah Lee. Date: . Last updated: .

This script rename all piped files to the file content's hash values.

This is useful when you have downloaded thousands of image files on the internet, and want to make sure you don't have duplicates.

Sample file name: 005662EE35110980CEDC1E5B1CD0E23B329C394A65E9134B2EBD0EAE3EC09DC3.jpg

function xah-rename-to-hash {

    # .DESCRIPTION
    # Rename each piped dir/file to the hash string of the file.
    # Must get arg from pipe.
    # If file base name is already hexstring and all caps and length 64, no rename is done.
    # .NOTES
    # Version: 2022-07-26 2022-09-05
    # .EXAMPLE
    # dir -file -filter *.jpg | xah-rename-to-hash
    # .LINK
    # http://xahlee.info/powershell/powershell_rename_file_to_hash.html

    Process {
        if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; }
        $leaf = Split-Path -Leaf $_;
        $leafBase = Split-Path -LeafBase $_;
        if ((64 -eq $leafBase.length) -and ($leafBase -cmatch "^[0-9A-F]+$")) {  }
        else {
            # Sample
            # 005662EE35110980CEDC1E5B1CD0E23B329C394A65E9134B2EBD0EAE3EC09DC3
            $ext = Split-Path -Extension $_;
            $newName = (Get-FileHash $_).hash + $ext;
            # Write-Host ($_.fullname + " → " + $newName)
            Write-Host ("$_ → $newName")
            Rename-Item $_ $newName
        }
    }
}