Even if i isn't the most elegant way, you could try something like this
$src = "$PSScriptRoot"
$file = "test.txt"
$dest = "$PSScriptRoot\dest"
$MAX_TRIES = 5
$copied = $false
for ($i = 1; $i -le $MAX_TRIES; $i++) {
if (!$copied) {
$safename = $file -replace "`.txt", "($i).txt"
if (!(Test-Path "$dest\$file")) {
Copy-Item "$src\$file" "$dest\$file"
$copied = $true
} elseif (!(Test-Path "$dest\$safename")) {
Copy-Item "$src\$file" "$dest\$safename"
$copied = $true
} else {
Write-Host "Found existing file -> checking for $safename"
}
} else {
break
}
}
- The
for-loop
will try to safely copy the file up to 5 times (determined by $MAX_TRIES
)
- If 5 times isn't enough, nothing will happen
- The
regEx
will create test(1).txt
, test(2).txt
, ... to check for a "safe" filename to copy
- The
if
-statement will check if the original file can be copied
- The
elseif
-statement will try to copy with the above created $safename
- The
else
-statement is just printing a "hint" on what's going on