我需要从文件中删除数字扩展名,同时不覆盖现有文件。
我该如何在 Powershell 中解决这个问题?
答案1
为了做到这一点,需要进行大量的代码操作:
(Get-ChildItem -Path "$env:USERPROFILE\Downloads").FullName -match '\([0-9]{1,4}\)' |
ForEach-Object {Rename-Item -Path $PSItem -NewName $($PSItem -replace '\([0-9]{1,4}\)') -WhatIf }
# Results
<#
What if: Performing the operation "Rename File" on target "Item: C:\...\How do I remove a single digit... (e.g. file (2).ext --- file.ext)...
Destination: C:\...\How do I remove a single digit, numbered suffix, in parenthesis (e.g. file .ext --- file.ext)...".
#>
删除 -WhatIf 以使事情发生
(Get-ChildItem -Path "$env:USERPROFILE\Downloads").FullName -match '\([0-9]{1,4}\)' |
ForEach-Object {Rename-Item -Path $PSItem -NewName $($PSItem -replace '\([0-9]{1,4}\)')}
# Results
<#
C:\...\How do I remove a single digit, numbered suffix, in parenthesis (e.g. file .ext --- file.ext) in Powershell- - Super User.url
#>
当然,只需使用修剪()处理不需要的空间的方法。
答案2
与问题相同的脚本:
get-childitem * -file -recurse | where-object {
$_.Name -match "^.*\([0-9]\)\.[^\.]*$"} | ForEach-Object {
$path=($_.Directory.tostring())
$ext=$_.Extension
$baseLen=($_.BaseName.Length)
$newLen=($baseLen-3)
$newBase=($_.basename.ToString().substring(0,$newLen))
if ($newBase.tostring().substring($newLen-1,1) -eq " ") {$newBase=($newBase.TrimEnd())}
$newFile=($path+"\"+$newBase+$ext)
if(!([system.io.file]::exists($newFile))) {Move-Item "$_" "$newFile"}
}