在 PowerShell 中重命名文件名

P4r1s

我想重命名已编辑照片的文件名,以便它们在 Windows 资源管理器中按顺序排列。

原来的文件名是这样的:IMG_1981.jpg编辑完后,它保存为:IMG_E1981.jpg

我想要实现的是E从编辑的文件名中删除并在文件名后添加一些增量。就像IMG_E1981.jpg越来越改为IMG_1981a.jpg或者IMG_1981(1).jpg,如果有匹配的文件名也以递增数。例如IMG_1981(2)IMG_1981(3)等等。

关于.ps实现这一目标的简单脚本有什么建议吗?

剃刀

在不太了解您当前的方法的情况下(请注意 Gerhard 的评论),您可以尝试以下操作

对于下面的测试脚本,我创建了一个包含脚本和子目录的新目录images该文件夹包含另一个名为renamed. 这使我们可以查看原始文件而无需重命名它们

$img_path = "$PSScriptRoot\images"
$rename_path = "$PSScriptRoot\images\renamed"

foreach ($img in (Get-ChildItem "$img_path\*.jpg")) {
    # note the single quotes at the end - otherwise you need to escape the $-sign
    $new_name = $img.Name -replace "_E(\d\d\d\d)", '_$1'

    # no image with that name exists
    if (!(Test-Path "$rename_path\$new_name")) {
        Copy-Item $img "$rename_path\$new_name"
    } else {
        # image-name already used
        $i = 1
        $inc_name = $new_name -replace ".jpg", "_$i.jpg"
        # creating a new image-name by appending _1, _2, etc. until
        # the name is not already used
        while (Test-Path "$rename_path\$inc_name") {
            Write-Host "Found $inc_name"
            $i++
            $inc_name = $new_name -replace ".jpg", "_$i.jpg"
        }
        Copy-Item $img "$rename_path\$inc_name"
    }
}

请记住,这肯定不是解决此问题的理想方法。请尝试更详细地解释您当前的问题。

既然您说要在文件名中添加类似(0)(1)的内容,如果它已经存在:为什么名称应该已经存在?随意分享演示目录内容:-)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章