使用Powershell重命名文件,文件名已存在

时间:2019-02-28 14:44:48

标签: powershell rename

我尝试通过删除-.extension

重命名多个文件夹中的批处理文件

示例文件:

  • 测试文件1-1234.docx
  • 测试文件1-4321.docx
  • 测试文件1-6-6789.docx

为此,我运行以下脚本:

Get-ChildItem -recurse -exclude .dxl | foreach { Rename-Item -Path $_.FullName -NewName (($_.BaseName -replace '(.)-.*?$','$1') + $_.Extension) }

这将给我以下错误:

  

“重命名项:当该文件已经存在时,无法创建该文件。”

如果重命名后文件已经存在,如何添加(1),(2),(3)来消除此问题?

1 个答案:

答案 0 :(得分:0)

这是我针对此问题想到的:

$FileTracker = @{}
$files = (Get-ChildItem  -recurse -exclude "*.dxl" -file | sort fullname).fullname
$files | foreach {
    $Base = (($_ | select-string -pattern "(.*)-.*?$").matches.groups[1].value).Trim()
    if ($FileTracker[$Base]) {
        Rename-Item -path $_ -newName ((split-Path $Base -Leaf),"($($FileTracker[$Base]))",($_ -replace ".*(\..*?)$",'$1') -join "")
        $FileTracker[$Base]++
    }
    else {
        $FileTracker.add($Base,1)
        Rename-Item -path $_ -newName ((split-path $Base -Leaf),($_ -replace ".*(\..*?)$",'$1') -join "")
    }

}

请记住,此解决方案旨在使文件在各自的目录中唯一。如果在两个不同的目录中看到test file 1 - 23.txt,它将把它们都重命名为test file 1.txt。如果您已经有testfile 1(1).txttestfile 1(2).txt之类的已重命名的文件,则此工作将存在问题。所以我需要知道这是否是一个条件。