I have a PowerShell script that flattens a directory structure and copies all files contained within.
ls $srcdir -Recurse | Where-Object {
$_.PSIsContainer -eq $false
} | foreach($_) {
cp $_.Fullname $destdir -Force -Verbose
}
I then took this and put it into a function.
function mcopy($srcdir, $destdir) {
ls $srcdir -Recurse | Where-Object {
$_.PSIsContainer -eq $false
} | foreach($_) {
cp $_.Fullname $destdir -Force -Verbose
}
}
I am now looking for a good way to handle duplicate file names within the function. By "handle" I mean incrementally altering the filename by adding a number to the file name if a file with that file name already exists in the destination directory.
I came across this in my search:
$SourceFile = "C:\Temp\File.txt"
$DestinationFile = "C:\Temp\NonexistentDirectory\File.txt"
if (Test-Path $DestinationFile) {
$i = 0
while (Test-Path $DestinationFile) {
$i += 1
$DestinationFile = "C:\Temp\NonexistentDirectory\File$i.txt"
}
} else {
New-Item -ItemType File -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force
I am trying to unify the concepts in both of these scripts but I have been unsuccessful so far.
function mcopy($srcdir, $destdir) {
ls $srcdir -Recurse | Where-Object {
$_.PSIsContainer -eq $false
} | foreach($_) {
if (Test-Path $_.fullname) {
$i = 0
while (Test-Path $_.fullname) {
$i += 1
$DestinationFile = "C:\Temp\NonexistentDirectory\File$i.txt"
}
} else {
New-Item -ItemType File -Path $_.fullname -Force
}
Copy-Item -Path $SourceFile -Destination $_.fullname -Force
}
}
I think I am missing something obvious or I've done something obviously wrong due to a misunderstanding somewhere.
Working substitute solutions (robocopy
or other) are also acceptable as long it both flattens the directory structure and handles duplicate file names well (please see definition of "well" further above).