2017-05-15 97 views
0

我想将每个文件从一个文件夹复制到另一个文件夹,并且如果该文件已存在,请在扩展前将其复制为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 
} 
+0

我试着把你的错别字和措辞,但目前还不清楚你在问什么你告诉我们你想要什么(或必须实现),但没有,在那里问题是 – Clijsters

+1

如果你想检查这个文件是否已经存在于旧路径中,那么使用一个带有Test-Path作为条件的'if'块,并且你的大部分子串逻辑都是不合逻辑的因为'Get-ChildItem' /'dir'返回的对象具有'extension'属性 – BenH

+0

对我的英语感到抱歉,这不是我的母语,它是我的第一个PS脚本。问题是,即使文件存在,它不被识别,我会尝试BenH的建议,并返回输出:)感谢您的帮助 – sohokai

回答

0

下面是一个更完整的解决方案是什么您正在尝试做评论在线:。

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

} 
+0

非常感谢,经过几次更改后,它运作良好:) – sohokai

相关问题