2016-06-07 52 views
0

存在我創建PS腳本文件僅在文件夾結構 - 遞歸重命名文件是否已經在PowerShell中

cp $source.Text -Recurse -Container:$false -destination $destination.Text 
$dirs = gci $destination.Text -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName 
$dirs | Foreach-Object { Remove-Item $_ } 

它工作正常複製。但問題是我有相同名稱的文件。它不會複製重複的文件。我需要重命名文件是否已經存在

來源:

folderA--> xxx.txt,yyy.txt, 
folderB-->xxx.txt,yyy.txt,zzz.txt, 
folderc-->xxx.txt 

目的地(要求)

xxx.txt 
xxx1.txt 
xxx2.txt 
yyy.txt 
yyy1.txt 
zzz.txt 

回答

0

在這裏,我通過文件名使用Group-Object cmdlet來組所有項目的解決方案。然後,我遍歷每個組,如果組包含一個以上的文件,我追加_$i到它那裏$i開始由一個並獲得遞增:

$source = $source.Text 
$destination = $destination.Text 


Get-ChildItem $source -File -Recurse | Group-Object Name | ForEach-Object { 
    if ($_.Count -gt 1) { # rename duplicated files 
     $_.Group | ForEach-Object -Begin {$i = 1} -Process { 
      $newFileName = $_.Name -replace '(.*)\.(.*)', "`$1_$i.`$2" 
      $i++ 
      Copy-Item -Path $_.FullName -Destination (Join-Path $destination $newFileName)    
     } 
    } 
    else # the filename is unique, just copy it. 
    { 
     $_.Group | Copy-Item -Destination $destination 
    } 
} 

注: 如果你的PowerShell您可以更改-File-Container:$false版本不支持它。另請注意,腳本不會查看目標文件夾是否存在具有相同名稱的文件。

相關問題