Last active
April 16, 2023 15:58
-
-
Save itsuki-hayashi/acbaa6e1283efe791b2bd5e22abe65ca to your computer and use it in GitHub Desktop.
Rename files in image set to simple numbers in a single folder with hash based deduplication (mostly for packing to zip files).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Specify the source directory containing the images | |
| $srcDir = ".\src" | |
| # Specify the destination directory to move the renamed images to | |
| $destDir = ".\dest" | |
| # Get all image files in the source directory and its subfolders | |
| $imageFiles = Get-ChildItem -Path $srcDir -Recurse -Include *.jpg,*.jpeg,*.png,*.gif,*.bmp | Sort-Object @{Expression={[regex]::Match($_.Name, '(\d+)').Groups[1].Value.PadLeft(10,'0')}},FullName | |
| # Get the number of digits needed to represent the count of files in $imageFiles | |
| $width = $imageFiles.Count.ToString().Length | |
| # Initialize a hashtable to store file hashes and their corresponding file paths | |
| $hashTable = @{} | |
| # Initialize a counter variable to keep track of the renamed files | |
| $count = 1 | |
| # Loop through each image file and rename it with an incremental number | |
| foreach ($file in $imageFiles) { | |
| # Calculate the hash of the file using the SHA256 algorithm | |
| $hash = Get-FileHash -LiteralPath "$($file.FullName)" -Algorithm SHA256 | Select-Object -ExpandProperty Hash | |
| # If the hash already exists in the hashtable, delete the file | |
| if ($hashTable.ContainsKey($hash)) { | |
| Write-Host "Skipping duplicate file: $($file.Name), skip" -ForegroundColor Yellow | |
| continue; | |
| } | |
| # Construct the new filename with the incremental number and file extension | |
| $newFilename = "{0:D$width}{1}" -f $count, $file.Extension | |
| # Construct the full path of the new file in the destination directory | |
| $newFilePath = Join-Path -Path $destDir -ChildPath $newFilename | |
| # Rename the file and move it to the destination directory | |
| Copy-Item -Path $file.FullName -Destination $newFilePath | |
| # Increment the counter variable | |
| $count++ | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment