Help with script removing (YEAR) from folder names.
Hello, the following script is working fine, except I cant get it to remove '(YEAR)' or '(YEAR)-(YEAR)' from the names, the other terms are working fine. This is the first half of a script I am working on to automate the import of manga for my manga library...
I have tried both Copilot and Gemini to try and fix this, no luck so far.
Edit: (****) does not work either...
Edit 2: Apologies, the code runs multiple times as there can be multiple terms, example starting name: Spy x Family (2020) (Digital) (1r0n)
Goal: Spy x Family
$SourceDir = "I:\test\complete test"
$CleanupTerms = @(
" (wangson)",
" (1r0n)",
" (LuCaZ)",
" (YameteOnii-sama)",
" (Shellshock)",
" (danke-Empire)",
" (Ushi)",
" (Oak)",
" (DigitalMangaFan)",
" (Stick)",
" (\d{4})", # Matches a four-digit year
" (\d{4})-(\d{4})", # Matches a range of years
" (Digital)",
" (Digital-Compilation)"
)
#Configure above for your own needs
#Below should not need to be touched
#This block of code will rename the folders in $SourceDir to remove the $CleanupTerms
foreach ($CleanupTerm in $CleanupTerms) {
$TrimmedCleanupTerm = $CleanupTerm.Trim()
Get-ChildItem -Path $SourceDir -Directory -Recurse |
Where-Object {$_.Name -clike "*$TrimmedCleanupTerm*"} |
ForEach-Object {
$NewName = $_.Name -replace [regex]::Escape($TrimmedCleanupTerm), ''
if ($_.Name -ne $NewName -and $NewName -ne '') {
if (-not (Test-Path -Path (Join-Path -Path $_.Parent.FullName -ChildPath $NewName))) {
Rename-Item -Path $_.FullName -NewName $NewName
Write-Host "Renamed $($_.FullName) to $NewName"
} else {
Write-Host "Skipping rename for $($_.FullName) as $NewName already exists."
}
}
}
}
Any help is appreciated, thanks!
Edit: Solved!
$SourceDir = "I:\test\complete test"
$CleanupTerms =
"\d{4}-\d{4}",
"\d{4}",
"wangson",
"1r0n",
"LuCaZ",
"YameteOnii-sama",
"Shellshock",
"danke-Empire",
"Ushi",
"Oak",
"DigitalMangaFan",
"Stick",
"Digital",
"Digital-Compilation"
$pattern = '\(({0})\)' -f ($CleanupTerms -join '|')
$MangaFolders = Get-ChildItem -Path $SourceDir -Directory | Select-Object -ExpandProperty Name
foreach ($MangaFolder in $MangaFolders) {
$NewName = $MangaFolder -replace $pattern -replace '\s+', ' ' -replace '^\s+|\s+$'
if ($MangaFolder -ne $NewName) {
Rename-Item -Path (Join-Path -Path $SourceDir -ChildPath $MangaFolder) -NewName $NewName
}
}