复制并重命名另一个目录上的文件

时间:2017-05-15 12:57:45

标签: powershell

我想将每个文件从一个文件夹复制到另一个文件夹,如果该文件已经存在,请在扩展前将其复制为2。正如@BenH告诉我的那样,我使用了测试路径和扩展属性,但它没有用2复制已经存在的文件,我无法弄清楚是什么错误

# 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
}

1 个答案:

答案 0 :(得分:1)

这是您尝试做的更完整的解决方案。评论内联:

$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
        }       
    }

}