Search code examples
powershellcopyrenameauto-increment

Copy files renaming if already exists PowerShell


This script works to rename files while copying them if they are duplicates. I need to rename the current destination file first then copy the source file as is. Any ideas?

function Copy-FilesWithVersioning{
    Param(
        [string]$source,
        [string]$destination
    )
    Get-ChildItem -Path $source -File
        ForEach-Object {
            $destinationFile = Join-Path $destination $file.Name
            if ($f = Get-Item $destinationFile -EA 0) {
                # loop for number goes here
                $i = 1
                $newname = $f.Name -replace $f.BaseName, "$($f.BaseName)_$I")
                Rename-Item $destinationFile $newName
            }
            Copy-Item $_ $destination
        }
}

Copy-FilesWithVersioning c:\scripts\Source c:\scripts\DestinationA

Errors:

At line:10 char:53
+             if($f = Get-Item $destinationFile -EA 0){
+                                                     ~
Missing closing '}' in statement block or type definition.
At line:8 char:23
+         ForEach-Object{
+                       ~
Missing closing '}' in statement block or type definition.
At line:2 char:34
+ function Copy-FilesWithVersioning{
+                                  ~
Missing closing '}' in statement block or type definition.
At line:13 char:77
+ ...         $newname = $f.Name -replace $f.BaseName, "$($f.BaseName)_$I")
+                                                                         ~
Unexpected token ')' in expression or statement.
At line:15 char:13
+             }
+             ~
Unexpected token '}' in expression or statement.
At line:17 char:9
+         }
+         ~
Unexpected token '}' in expression or statement.
At line:18 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndCurlyBrace

Solution

  • Try code from this link: https://www.pdq.com/blog/copy-individual-files-and-rename-duplicates/:

    $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