重命名Powershell文件,无法重命名文件不存在

时间:2019-03-05 18:09:59

标签: regex powershell

我尝试以递归方式从一堆文件中删除“-13234”。如果删除该部分后该文件已经存在,则应在新文件名之后添加(1),(2)等。

我在少量文件上进行了测试,效果很好。现在,我在更大的测试仪上进行了尝试,但它给了我一些错误。

赞:无法重命名文件不存在 就像:文件已经存在时无法创建文件

对于许多文件来说,实际上看起来还不错。

$files = Get-ChildItem <location> -recurse -file | sort name | group-object -property {$_.fullname -replace "(.*)-.*?(\..*?)$",'$1$2'}
$files | foreach {
    $inc = 0

    if ($_.count -gt 1) {
        rename-item -literalpath $_.group[0].fullname -NewName (($_.group[0].basename -replace "(.*)-.*?$",'$1') + $_.group[0].extension)
        $inc++

    for ($i = $inc; $i -lt $_.count; $i++) {

        rename-item -literalpath $_.group[$i].fullname -NewName (($_.group[$i].basename -replace "(.*)-.*?$",'$1') + "($i)" + $_.group[$i].extension)
    }
    }
    else {
        rename-item -literalpath $_.group.fullname -NewName (($_.group.basename -replace "(.*)-.*?$",'$1') + $_.group.extension)   
}
}

2 个答案:

答案 0 :(得分:0)

如果以下文件位于同一目录中,则该脚本可能无法正常工作。

1 - 13234.txt
1.txt

该脚本首先尝试将“ 1-13234.txt”更改为“ 1. txt”。 最好先检查文件是否存在。

Get-ChildItem -File -Recurse |
where BaseName -match "(.*)-" |
Group-Object { $_.DirectoryName + "\" + $Matches[1].TrimEnd() + $_.Extension } |
foreach {
    $fi = [IO.FileInfo]::new($_.Name)
    $i = 0
    $_.Group | Rename-Item -NewName {
        do {
            $newName = $fi.DirectoryName + "\" + $fi.BaseName + $(if($i){"($i)"}) + $fi.Extension
            $script:i++
        } while (Test-Path $newName)
        $newName
    } -PassThru
}

答案 1 :(得分:0)

我会做这样的事情:

$Path = '<PATH TO THE ROOTFOLDER WHERE THE FILES TO RENAME ARE FOUND>'

Get-ChildItem -Path $Path -Filter '*-*' -File -Recurse | ForEach-Object {
    # obtain the new file basename
    $newBaseName = ($_.BaseName -split '-')[0].Trim()
    $extension   = $_.Extension    # this includes the dot
    $folder      = $_.DirectoryName

    # get an array of all filenames (name only) of the files with a similar name already present in the folder
    $allFiles = @(Get-ChildItem $folder -Filter "$newBaseName*$extension" -File | Select-Object -ExpandProperty Name)
    # for PowerShell version < 3.0 use this
    # $allFiles = @(Get-ChildItem $folder-Filter "$newBaseName*$extension" | Where-Object { !($_.PSIsContainer) } | Select-Object -ExpandProperty Name)

    # construct the new filename
    $newFileName = $newBaseName + $extension

    if ($allFiles.Count) {
        $count = 1
        while ($allFiles -contains $newFileName) {
            $newFileName = "{0}({1}){2}" -f $newBaseName, $count++, $extension
        }
    }

    Write-Host "Renaming '$($_.FullName)' to '$newFileName'"
    $_ | Rename-Item -NewName $newFileName -Force
}

希望有帮助