sohokai
sohokai

Reputation: 55

Copy and rename files on another directory

I want to copy every file from one folder to another folder, and if the file already exists, copy it with a 2 before the extention. as @BenH told me i used test-path and extension properties but it doesn't copy an already existing file with 2, and i can"t figure out what's wrong

# script to COPY and RENAME if files already exists
try {
    Clear-Host
    Write-Host " -- process start --"

    $usersPath = "C:\Users\mhanquin\Desktop\test_PS\users\mhanquin"
    $oldPath = "C:\Users\mhanquin\Desktop\test_PS\OLD\mhanquin"

    $folders = dir $usersPath
    $files = dir $oldPath

    foreach ($d in $folders) { 
        $z = test-path $files\$d

        if($z -eq $true){
            $c.basename = $d.basename + "2"
            $c.extension = $d.extension          
            rename-item $userspath\$d -newname $c
            copy-item $userspath\$c $oldpath
        }    
        else{ copy-item $userspath\$d $oldpath }
    }
    Write-Host "---Done---"
} catch {
    Write-Host "ERROR -"$_.Exception.Message
    break
}

Upvotes: 0

Views: 538

Answers (1)

BenH
BenH

Reputation: 10044

Here is a more complete solution for what you are attempting to do. Comments inline:

$UserPath = "C:\Users\mhanquin\Desktop\test_PS\users\mhanquin"
$OldPath = "C:\Users\mhanquin\Desktop\test_PS\OLD\mhanquin"

$UserItems = Get-ChildItem $UserPath -Recurse

foreach ($UserItem in $UserItems) {
    #Escape the Regex pattern to handle / in paths
    $UserPathRegEx = [Regex]::Escape($usersPath)
    #Use a replace Regex to remove UserPath and leave a relative path 
    $RelativePath = $UserItem.FullName -replace $UserPathRegEx,""
    #Join the Destination and the Relative Path
    $Destination = Join-Path $OldPath $RelativePath
    #Test if it is a directory
    if ($UserItem.PSIsContainer) {
        if (!(Test-Path $Destination)) {
            New-Item $Destination -Type Directory
        }
    } else {
        if (Test-Path $Destination) {
            #Rather than use just a 2, get a timestamp for duplicates
            $TimeStamp = Get-Date -Format MMddhhmm
            #Using subexpression $() to evaluate the variable properties inside a string
            $NewFileName = "$($usersItem.basename).$TimeStamp$($usersItem.extension)"
            #For the rename, join the Directory with the new file name for the new destination
            $NewDestination = Join-Path $($Destination.Directory.fullname) $newFileName
            Rename-Item $Destination -newname $NewDestination
            Copy-Item $UserItem.fullname $Destination
        } else {
            Copy-Item $UserItem.fullname $Destination
        }       
    }

}

Upvotes: 1

Related Questions