【问题标题】:Rename files with Powershell, file name already exist用Powershell重命名文件,文件名已经存在
【发布时间】:2019-07-22 12:26:06
【问题描述】:

我尝试通过删除 - .extension 来重命名多个文件夹中的批处理文件

示例文件:

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

为此,我运行以下脚本:

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

这会给我以下错误:

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

如果重命名后文件已经存在,如何通过添加 (1)、(2)、(3) 来消除这种情况?

【问题讨论】:

  • 类似while (Test-Path $f) { $c++ ; $f="$n ($c)"}
  • Test-Path 将让您检查文件是否已存在。不要立即尝试重命名,而是将您传递给-NewName 的表达式分配给字符串变量,然后使用Test-Path,并修改字符串变量的值,直到Test-Path 告诉您它没有'不存在 - 然后执行Rename-Item
  • 看看我的Copy-Unique函数。希望对您有所帮助。
  • 答案已被接受,因此我假设发布的解决方案正在工作,如果没有回复,我可能有其他答案

标签: powershell rename


【解决方案1】:

这是我为这个问题想出来的:

$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 这样重命名的文件,那么这个工作会出现问题。所以我需要知道这是否是一个条件。

【讨论】:

  • 这还有两个问题,不排除 .dxl 文件,如果有两个文件 - 在文件名中,它不仅是最后一个“-”之后的切割部分。
  • 如果有多个文件,例如: - 1234 , - 2314, -2231 它也会失败:(
  • 遗憾的是,这并不能完全解决问题。对于两种类型的文件,它不起作用。 - 像 // - 12457 >> 结果: - 12457(1) - 像 // Re_testfile test - test - test - 12458 >> 结果: Re_testfile test
  • 当你有一个像“testfile test - test - test - test - 1223.docx”这样的文件时,你希望它如何重命名?
  • 只想删除最后一部分 - ,所以最后一个“-”之后的所有内容。
猜你喜欢
  • 2015-06-14
  • 2023-04-06
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 2015-11-26
相关资源
最近更新 更多