-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path004-copies_files_from_source_to_destination.ps1
More file actions
485 lines (417 loc) · 19.3 KB
/
Copy path004-copies_files_from_source_to_destination.ps1
File metadata and controls
485 lines (417 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# =====================================
# SCRIPT CREDITS
# =====================================
# Author: Benjamin Ohene-Adu
# Name of Script: 004-copies_files_from_source_to_destination.ps1
# Creation Date: October 31, 2025
# Intent of script: Utility script for copying or moving files from source to destination with comprehensive validation, progress tracking, and error handling.
# =====================================
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory=$false, Position=0, HelpMessage="Source folder path containing files to copy/move")]
[ValidateScript({
if (-not (Test-Path $_)) {
throw "Source folder does not exist: $_"
}
if (-not (Test-Path $_ -PathType Container)) {
throw "Source path is not a directory: $_"
}
$true
})]
[string]$SourceFolder = "E:\MUSIC\Reggae",
[Parameter(Mandatory=$false, Position=1, HelpMessage="Destination folder path where files will be copied/moved")]
[ValidateNotNullOrEmpty()]
[string]$DestinationFolder = "C:\OrganizedMusic\DUPLICATES\Reggae",
[Parameter(Position=2, HelpMessage="Operation to perform: Copy or Move files")]
[ValidateSet("Copy", "Move")]
[string]$Operation = "Copy",
[Parameter(Position=3, HelpMessage="Action when destination file exists: Skip, Overwrite, Rename, or Compare")]
[ValidateSet("Skip", "Overwrite", "Rename", "Compare")]
[string]$DuplicateAction = "Skip",
[Parameter(Position=4, HelpMessage="Folder structure handling: Preserve or Flatten directory structure")]
[ValidateSet("Preserve", "Flatten")]
[string]$FolderStructure = "Preserve",
[Parameter(HelpMessage="File extensions to include (e.g., '.mp3','.flac'). If empty, all files included")]
[string[]]$IncludeExtensions = @(),
[Parameter(HelpMessage="File extensions to exclude (e.g., '.tmp','.log')")]
[string[]]$ExcludeExtensions = @(),
[Parameter(HelpMessage="Minimum file size in bytes. Files smaller than this will be skipped")]
[long]$MinFileSize = 0,
[Parameter(HelpMessage="Maximum file size in bytes. Files larger than this will be skipped")]
[long]$MaxFileSize = [long]::MaxValue,
[Parameter(HelpMessage="Only process files modified after this date")]
[datetime]$ModifiedAfter,
[Parameter(HelpMessage="Only process files modified before this date")]
[datetime]$ModifiedBefore,
[Parameter(HelpMessage="Preview operations without executing them")]
[switch]$DryRun,
[Parameter(HelpMessage="Create detailed log file of all operations")]
[switch]$EnableLogging,
[Parameter(HelpMessage="Path for log file. Defaults to script directory")]
[string]$LogPath,
[Parameter(HelpMessage="Continue processing even if individual file operations fail")]
[switch]$ContinueOnError
)
# Initialize logging if enabled
if ($EnableLogging -and -not $LogPath) {
$LogPath = Join-Path $PSScriptRoot "file_operations_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
}
# Validate parameters
if ($ModifiedAfter -and $ModifiedBefore -and $ModifiedAfter -gt $ModifiedBefore) {
throw "ModifiedAfter date cannot be later than ModifiedBefore date"
}
if ($MinFileSize -gt $MaxFileSize) {
throw "MinFileSize cannot be greater than MaxFileSize"
}
# Normalise extensions to include dots
if ($IncludeExtensions) {
$IncludeExtensions = $IncludeExtensions | ForEach-Object {
if (-not $_.StartsWith('.')) { ".$_" } else { $_ }
}
}
if ($ExcludeExtensions) {
$ExcludeExtensions = $ExcludeExtensions | ForEach-Object {
if (-not $_.StartsWith('.')) { ".$_" } else { $_ }
}
}
# Function to write log entries
function Write-LogEntry {
param([string]$Message, [string]$Level = "INFO")
if ($EnableLogging) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
Add-Content -Path $LogPath -Value $logEntry -Encoding UTF8
}
}
# Function to test if file meets filtering criteria
function Test-FileFilter {
param([System.IO.FileInfo]$File)
# Check extension filters
if ($IncludeExtensions -and $File.Extension -notin $IncludeExtensions) {
return $false
}
if ($ExcludeExtensions -and $File.Extension -in $ExcludeExtensions) {
return $false
}
# Check size filters
if ($File.Length -lt $MinFileSize -or $File.Length -gt $MaxFileSize) {
return $false
}
# Check date filters
if ($ModifiedAfter -and $File.LastWriteTime -lt $ModifiedAfter) {
return $false
}
if ($ModifiedBefore -and $File.LastWriteTime -gt $ModifiedBefore) {
return $false
}
return $true
}
# Function for smart file comparison (only hash when sizes match)
function Compare-Files {
param(
[System.IO.FileInfo]$SourceFile,
[System.IO.FileInfo]$DestinationFile
)
# Quick check: different sizes = definitely different files
if ($SourceFile.Length -ne $DestinationFile.Length) {
return $false
}
# Same size - need to check content via hash (expensive operation)
Write-Host " [*] Same size detected, calculating hashes..." -ForegroundColor DarkGray
Write-LogEntry "Calculating hashes for size-matched files: $($SourceFile.FullName) vs $($DestinationFile.FullName)"
try {
$sourceHash = (Get-FileHash -Path $SourceFile.FullName -Algorithm SHA256).Hash
$destHash = (Get-FileHash -Path $DestinationFile.FullName -Algorithm SHA256).Hash
return $sourceHash -eq $destHash
}
catch {
Write-Warning "Failed to calculate hash for comparison: $($_.Exception.Message)"
Write-LogEntry "Hash calculation failed: $($_.Exception.Message)" "ERROR"
return $false
}
}
# Counters for reporting
$script:FilesProcessed = 0
$script:FilesSkipped = 0
$script:FilesOverwritten = 0
$script:FilesRenamed = 0
$script:FilesNew = 0
$script:FilesMoved = 0
# Track operation timing
$startTime = Get-Date
# Create the destination folder if it doesn't exist
if (-not (Test-Path -Path $DestinationFolder)) {
New-Item -ItemType Directory -Path $DestinationFolder | Out-Null
Write-Host "[+] Created destination folder: $DestinationFolder" -ForegroundColor Green
}
# Function to perform the file operation (copy or move)
function Invoke-FileOperation {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$SourcePath,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$DestinationPath,
[Parameter(Mandatory=$true)]
[ValidateSet("Copy", "Move")]
[string]$Operation,
[switch]$Force
)
# Validate that source file exists
if (-not (Test-Path -Path $SourcePath)) {
$message = "Source file does not exist: $SourcePath"
Write-Warning $message
Write-LogEntry $message "ERROR"
return $false
}
# Dry run mode - just log what would happen
if ($DryRun) {
$action = if ($Operation -eq "Move") { "WOULD MOVE" } else { "WOULD COPY" }
$forceText = if ($Force) { " (FORCE)" } else { "" }
Write-Host "[DRY RUN] $action`: $SourcePath -> $DestinationPath$forceText" -ForegroundColor Magenta
Write-LogEntry "DRY RUN: $action $SourcePath -> $DestinationPath$forceText"
return $true
}
try {
if ($PSCmdlet.ShouldProcess($DestinationPath, $Operation)) {
if ($Operation -eq "Move") {
if ($Force) {
Move-Item -Path $SourcePath -Destination $DestinationPath -Force
} else {
Move-Item -Path $SourcePath -Destination $DestinationPath
}
$script:FilesMoved++
} else {
if ($Force) {
Copy-Item -Path $SourcePath -Destination $DestinationPath -Force
} else {
Copy-Item -Path $SourcePath -Destination $DestinationPath
}
}
$action = if ($Operation -eq "Move") { "MOVED" } else { "COPIED" }
Write-LogEntry "$action`: $SourcePath -> $DestinationPath"
return $true
}
}
catch {
$message = "Failed to $($Operation.ToLower()) file: $SourcePath -> $DestinationPath. Error: $($_.Exception.Message)"
Write-Warning $message
Write-LogEntry $message "ERROR"
if (-not $ContinueOnError) {
throw $_
}
return $false
}
}
# Start file operation
$operationVerb = if ($Operation -eq "Move") { "moving" } else { "copying" }
Write-Host "[*] Starting file $operationVerb operation..." -ForegroundColor Yellow
if ($DryRun) {
Write-Host "[*] DRY RUN MODE - No files will be modified" -ForegroundColor Magenta
}
Write-Host "[*] Source: $SourceFolder" -ForegroundColor Cyan
Write-Host "[*] Destination: $DestinationFolder" -ForegroundColor Cyan
Write-Host "[*] Operation: $Operation" -ForegroundColor Yellow
Write-Host "[*] Duplicate Action: $DuplicateAction" -ForegroundColor Yellow
Write-Host "[*] Folder Structure: $FolderStructure" -ForegroundColor Yellow
if ($IncludeExtensions) {
Write-Host "[*] Include Extensions: $($IncludeExtensions -join ', ')" -ForegroundColor Green
}
if ($ExcludeExtensions) {
Write-Host "[*] Exclude Extensions: $($ExcludeExtensions -join ', ')" -ForegroundColor Red
}
if ($MinFileSize -gt 0 -or $MaxFileSize -lt [long]::MaxValue) {
Write-Host "[*] Size Filter: $MinFileSize - $MaxFileSize bytes" -ForegroundColor Cyan
}
if ($ModifiedAfter -or $ModifiedBefore) {
$dateFilter = "Modified: "
if ($ModifiedAfter) { $dateFilter += "after $($ModifiedAfter.ToString('yyyy-MM-dd')) " }
if ($ModifiedBefore) { $dateFilter += "before $($ModifiedBefore.ToString('yyyy-MM-dd'))" }
Write-Host "[*] $dateFilter" -ForegroundColor Cyan
}
Write-Host ""
# Initialize logging
if ($EnableLogging) {
Write-LogEntry "Starting $Operation operation from '$SourceFolder' to '$DestinationFolder'"
Write-LogEntry "Parameters: DuplicateAction=$DuplicateAction, FolderStructure=$FolderStructure, DryRun=$DryRun"
}
$allFilesUnfiltered = Get-ChildItem -Path $SourceFolder -Recurse -File
$totalFilesFound = $allFilesUnfiltered.Count
$allFiles = $allFilesUnfiltered | Where-Object { Test-FileFilter $_ }
$totalFiles = $allFiles.Count
$currentFile = 0
Write-Host "[*] Found $totalFilesFound files total, $totalFiles files to process (after filtering)" -ForegroundColor Green
if ($EnableLogging) {
Write-LogEntry "Found $totalFilesFound files total, $totalFiles files to process after filtering"
}
Write-Host ""
$allFiles | ForEach-Object {
$currentFile++
$script:FilesProcessed++
# Capture current file object to avoid scope issues
$currentFileObj = $_
$sourceFilePath = $currentFileObj.FullName
# Determine file paths based on folder structure setting
if ($FolderStructure -eq "Flatten") {
# Flatten: Use just the filename, no subdirectories
$fileName = [System.IO.Path]::GetFileName($sourceFilePath)
$RelativePath = $fileName
$DestinationPath = Join-Path -Path $DestinationFolder -ChildPath $fileName
$DestinationDir = $DestinationFolder
} else {
# Preserve: Keep original subdirectory structure
$RelativePath = $sourceFilePath.Substring($SourceFolder.Length).TrimStart('\')
$DestinationPath = Join-Path -Path $DestinationFolder -ChildPath $RelativePath
$DestinationDir = Split-Path -Path $DestinationPath -Parent
}
# Show progress
$percentComplete = [math]::Round(($currentFile / $totalFiles) * 100, 1)
$progressActivity = if ($Operation -eq "Move") { "Moving Files" } else { "Copying Files" }
Write-Progress -Activity $progressActivity -Status "Processing: $RelativePath" -PercentComplete $percentComplete
# Ensure destination directory exists
if (-not (Test-Path -Path $DestinationDir)) {
New-Item -ItemType Directory -Path $DestinationDir -Force | Out-Null
}
# Check if destination file already exists
if (Test-Path -Path $DestinationPath) {
$sourceFile = Get-Item $sourceFilePath
$destFile = Get-Item $DestinationPath
switch ($DuplicateAction) {
"Skip" {
Write-Host "[-] SKIPPED: $RelativePath (already exists)" -ForegroundColor Yellow
$script:FilesSkipped++
return
}
"Overwrite" {
Invoke-FileOperation -SourcePath $sourceFilePath -DestinationPath $DestinationPath -Operation $Operation -Force
$actionText = if ($Operation -eq "Move") { "MOVED" } else { "OVERWRITTEN" }
Write-Host "[!] $actionText`: $RelativePath" -ForegroundColor DarkYellow
$script:FilesOverwritten++
return
}
"Rename" {
$counter = 1
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($DestinationPath)
$extension = [System.IO.Path]::GetExtension($DestinationPath)
$directory = [System.IO.Path]::GetDirectoryName($DestinationPath)
do {
$newName = "$baseName ($counter)$extension"
$newDestinationPath = Join-Path -Path $directory -ChildPath $newName
$counter++
} while (Test-Path -Path $newDestinationPath)
Invoke-FileOperation -SourcePath $sourceFilePath -DestinationPath $newDestinationPath -Operation $Operation -Force
if ($FolderStructure -eq "Flatten") {
$newRelativePath = [System.IO.Path]::GetFileName($newDestinationPath)
} else {
$newRelativePath = $newDestinationPath.Substring($DestinationFolder.Length).TrimStart('\')
}
$actionText = if ($Operation -eq "Move") { "MOVED" } else { "RENAMED" }
Write-Host "[*] $actionText`: $RelativePath -> $newRelativePath" -ForegroundColor Magenta
$script:FilesRenamed++
return
}
"Compare" {
# Smart comparison: check if files are identical
if (Compare-Files -SourceFile $sourceFile -DestinationFile $destFile) {
Write-Host "[=] IDENTICAL: $RelativePath (same content, skipping)" -ForegroundColor Green
Write-LogEntry "IDENTICAL: Skipped $RelativePath (files have identical content)"
$script:FilesSkipped++
return
} else {
# Files are different - use timestamp to decide which to keep
if ($sourceFile.LastWriteTime -gt $destFile.LastWriteTime) {
Invoke-FileOperation -SourcePath $sourceFilePath -DestinationPath $DestinationPath -Operation $Operation -Force
$actionText = if ($Operation -eq "Move") { "MOVED" } else { "UPDATED" }
Write-Host "[^] $actionText`: $RelativePath (newer version)" -ForegroundColor Blue
$script:FilesOverwritten++
} else {
Write-Host "[-] SKIPPED: $RelativePath (destination is newer)" -ForegroundColor Yellow
Write-LogEntry "SKIPPED: $RelativePath (destination file is newer)"
$script:FilesSkipped++
}
return
}
}
}
} else {
# File doesn't exist at destination - copy or move it
Invoke-FileOperation -SourcePath $sourceFilePath -DestinationPath $DestinationPath -Operation $Operation
$actionText = if ($Operation -eq "Move") { "MOVED" } else { "COPIED" }
Write-Host "[+] $actionText`: $RelativePath" -ForegroundColor Green
$script:FilesNew++
}
}
$progressActivity = if ($Operation -eq "Move") { "Moving Files" } else { "Copying Files" }
Write-Progress -Activity $progressActivity -Completed
# Final summary report
$endTime = Get-Date
$duration = $endTime - $startTime
$totalSizeProcessed = 0
# Calculate total size processed
$allFiles | ForEach-Object { $totalSizeProcessed += $_.Length }
$totalSizeMB = [math]::Round($totalSizeProcessed / 1MB, 2)
Write-Host ""
Write-Host ("=" * 60) -ForegroundColor Cyan
$summaryTitle = if ($DryRun) {
"DRY RUN SUMMARY - NO FILES WERE MODIFIED"
} elseif ($Operation -eq "Move") {
"MOVE OPERATION SUMMARY"
} else {
"COPY OPERATION SUMMARY"
}
Write-Host $summaryTitle -ForegroundColor Yellow
Write-Host ("=" * 60) -ForegroundColor Cyan
Write-Host "Start Time: $($startTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor White
Write-Host "End Time: $($endTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor White
Write-Host "Duration: $($duration.ToString('hh\:mm\:ss'))" -ForegroundColor White
Write-Host "Source: $SourceFolder" -ForegroundColor White
Write-Host "Destination: $DestinationFolder" -ForegroundColor White
Write-Host "Operation: $Operation" -ForegroundColor White
Write-Host "Duplicate Action: $DuplicateAction" -ForegroundColor White
Write-Host "Folder Structure: $FolderStructure" -ForegroundColor White
if ($IncludeExtensions) {
Write-Host "Include Extensions: $($IncludeExtensions -join ', ')" -ForegroundColor White
}
if ($ExcludeExtensions) {
Write-Host "Exclude Extensions: $($ExcludeExtensions -join ', ')" -ForegroundColor White
}
Write-Host ""
Write-Host "RESULTS:" -ForegroundColor Yellow
Write-Host " Total files found: $totalFilesFound" -ForegroundColor White
Write-Host " Total files processed: $script:FilesProcessed" -ForegroundColor White
Write-Host " Total size processed: $totalSizeMB MB" -ForegroundColor White
if ($Operation -eq "Move") {
Write-Host " Files moved: $script:FilesNew" -ForegroundColor Green
if ($script:FilesMoved -gt 0) {
Write-Host " Additional moves: $script:FilesMoved" -ForegroundColor Green
}
} else {
Write-Host " New files copied: $script:FilesNew" -ForegroundColor Green
}
Write-Host " Files skipped: $script:FilesSkipped" -ForegroundColor Yellow
Write-Host " Files overwritten: $script:FilesOverwritten" -ForegroundColor DarkYellow
Write-Host " Files renamed: $script:FilesRenamed" -ForegroundColor Magenta
# Calculate processing rate
if ($duration.TotalSeconds -gt 0) {
$filesPerSecond = [math]::Round($script:FilesProcessed / $duration.TotalSeconds, 2)
$mbPerSecond = [math]::Round($totalSizeMB / $duration.TotalSeconds, 2)
Write-Host " Processing rate: $filesPerSecond files/sec, $mbPerSecond MB/sec" -ForegroundColor Cyan
}
Write-Host ""
# Final logging and completion message
if ($EnableLogging) {
Write-LogEntry "Operation completed. Processed: $script:FilesProcessed, New: $script:FilesNew, Skipped: $script:FilesSkipped, Overwritten: $script:FilesOverwritten, Renamed: $script:FilesRenamed"
Write-LogEntry "Total size processed: $totalSizeMB MB in $($duration.ToString('hh\:mm\:ss'))"
Write-Host " Detailed log saved to: $LogPath" -ForegroundColor Cyan
}
$completionMessage = if ($DryRun) {
"[+] Dry run completed - review actions above!"
} elseif ($Operation -eq "Move") {
"[+] Move operation completed successfully!"
} else {
"[+] Copy operation completed successfully!"
}
Write-Host $completionMessage -ForegroundColor Green
Write-Host ("=" * 60) -ForegroundColor Cyan