Skip to content

Instantly share code, notes, and snippets.

@mmodrow
Last active September 25, 2024 07:52
Show Gist options
  • Save mmodrow/515b678b962abf07632d627d0e187775 to your computer and use it in GitHub Desktop.
Save mmodrow/515b678b962abf07632d627d0e187775 to your computer and use it in GitHub Desktop.
copy files and rename them by creation time stamp conflict-free
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$source,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$destination,
[string]
$location,
[switch]
$skipDuplicates = $false,
[switch]
$overrideTimeWithNow = $false
)
if (!$source) {
$source = Join-Path $PSScriptRoot "102PANA"
}
if ($location) {
$location = "_" + $location
}
$files = Get-ChildItem -Path $source
$fileCount = $files.count
$currentIndex = 0
$groups = ($files | Sort-Object -Property Name | Group-Object -Property extension,@{ expression={$_.lastWriteTime}})
for ($i = 0; $i -lt $groups.Count; $i++) {
$group = $groups[$i].Group
$count = $groups[$i].Count
$padLeft = ([Int32]$count).ToString().Count
for ($j = 0; $j -lt $count; $j++) {
$file = $group[$j]
$suffix = if ($count -gt 1) { "_" + ([Int32]$j + 1).ToString().PadLeft($padLeft, '0') } else { "" }
$suffix = $suffix + $location
$time = $file.CreationTime.ToString("yyyy-MM-dd_HH-mm-ss")
if ($overrideTimeWithNow) {
$time = Get-date -format "yyyy-MM-dd_HH-mm-ss"
}
$targetFileName = $time + $suffix + $file.Extension.ToLower()
$targetPath = Join-Path $destination $targetFileName
$percentComplete = [int](($currentIndex++ / $fileCount) * 100)
$statusMessage = "From: " + $file.FullName + " to: " + $targetPath
Write-Progress -Activity "Copying Files" -PercentComplete $percentComplete -Status "$percentComplete% Complete. Current Item: $statusMessage"
Write-Host $statusMessage
if (Test-Path $targetPath) {
if ($skipDuplicates) {
Write-Host "$targetPath exists and existing files are set to be skipped. Skipping file."
continue
}
elseif ((Get-FileHash -Path $file.FullName -Algorithm MD5).Hash -eq (Get-FileHash -Path $targetPath -Algorithm MD5).Hash) {
Write-Host "$targetPath exists with different content. Skipping file."
continue
}
}
Copy-Item -Path $file.FullName -Destination $targetPath
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment