2017-05-15 96 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

相關問題