Keep/Rename Duplicate Items with Copy

2019-08-29 16:33发布

问题:

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).

回答1:

Thanks to the advice I received when I asked this question I found I was making a few simple errors and I just needed to refine the scripting a little bit more.

The corrected script is below. Thus far it has worked a treat on smaller data sets. I will be testing it on some larger directories soon!

function mcopy($srcdir,$destdir)
{
ls $srcdir -recurse | Where-Object { $_.PSIsContainer -eq $false } | foreach($_) {
$SourceFile = $_.FullName
$DestinationFile = $destdir+$_
If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = $destdir+$_+$i
    }
} Else {
    New-Item -ItemType File -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -verbose -Force
}
}

mcopy -srcdir C:\copyme\ -destdir C:\copyharder\