我使用 ChatGPT 编写了一个脚本,将文件名的一部分从“SF78”重命名为“Medical”,并在文件名末尾添加序列 (1) 等。不幸的是,它并不是 100% 成功。该序列将添加到文件扩展名之后。
我尝试使用 $file.BaseName 来不包含扩展名,然后在加入 $file.basename、序列和文件扩展名后添加扩展名。似乎什么都不起作用。当我距离如此之近时,它必须是特定位置的最小设置,但就是无法正确设置。
这是脚本:
```
$folderPath = $filePath
$files = Get-ChildItem -Path $folderPath -File | Where-Object { $_.Name -match 'SF78' }
foreach ($file in $files) {
$originalName = $file
$newName = $originalName -replace 'SF78', 'MEDICAL'
# Check if a file with the new name already exists
$counter = 1
while (Test-Path (Join-Path -Path $folderPath -ChildPath $newName)) {
$testName = $originalName -replace 'SF78', 'MEDICAL'
$newName = (($testName, ($counter)) -join ' ') + $file.extension
$counter++
}
# Rename the file
$newPath = Join-Path -Path $folderPath -ChildPath $newName
Rename-Item -Path $file.FullName -NewName $newName
Write-Host "Renamed $($originalName) to $($newName)"
}
```
尝试使用这个脚本。我已经修改了
$folderPath = $filePath
$files = Get-ChildItem -Path $folderPath -File | Where-Object { $_.Name -match 'SF78' }
foreach ($file in $files) {
$originalName = $file.Name
$basename = $file.BaseName
$extension = $file.Extension
$newName = $basename -replace 'SF78', 'MEDICAL'
# Check if a file with the new name already exists
$counter = 1
while (Test-Path (Join-Path -Path $folderPath -ChildPath "$newName$extension")) {
$newName = "$basename ( $counter )" # Add sequence within parentheses before extension
$counter++
}
# Rename the file
$newPath = Join-Path -Path $folderPath -ChildPath "$newName$extension"
Rename-Item -Path $file.FullName -NewName $newPath
Write-Host "Renamed $($originalName) to $newName"
}