Regex 看起来很有希望。我故意排除了它们,但我更改了代码以包含它们。此外,我每次都更改为检查现有文件名。这在使用更大的测试集时不会出现错误。只有以下结构为“-664569”作为BaseName的文件不会被拾取。对于其余部分,这看起来很有希望。我故意排除了它们,但我
Regex 看起来很有希望。我故意排除了它们,但我更改了代码以包含它们。此外,我每次都更改为检查现有文件名。这在使用更大的测试集时不会出现错误。只有以下结构为“-664569”作为BaseName的文件不会被拾取。对于其余部分,这看起来很有希望。我故意排除了它们,但我,regex,powershell,Regex,Powershell,看起来很有希望。我故意排除了它们,但我更改了代码以包含它们。此外,我每次都更改为检查现有文件名。这在使用更大的测试集时不会出现错误。只有以下结构为“-664569”作为BaseName的文件不会被拾取。对于其余部分,这看起来很有希望。我故意排除了它们,但我更改了代码以包含它们。另外,我每次都会检查现有的文件名。 $files = Get-ChildItem <location> -recurse -file | sort name | group-object -property {
看起来很有希望。我故意排除了它们,但我更改了代码以包含它们。此外,我每次都更改为检查现有文件名。这在使用更大的测试集时不会出现错误。只有以下结构为“-664569”作为BaseName的文件不会被拾取。对于其余部分,这看起来很有希望。我故意排除了它们,但我更改了代码以包含它们。另外,我每次都会检查现有的文件名。
$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)
}
}
1 - 13234.txt
1.txt
$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
}