I got this script that is supposed to go through my media library and clean up the names of the episodes of an series. But no matter what I try the script can’t find any files. Script in question:
# Define the base directory
$baseDir = Get-Location
# Get all subdirectories in the base directory
$directories = Get-ChildItem -Path $baseDir -Directory
foreach ($dir in $directories) {
Write-Host "Processing directory: $($dir.FullName)"
# List all contents of the current directory
$contents = Get-ChildItem -Path $dir.FullName
Write-Host "Contents of directory: $($dir.FullName)"
foreach ($content in $contents) {
Write-Host " Item: $($content.Name) - Type: $($content.GetType().Name)"
}
# Get all files in the current directory
$files = Get-ChildItem -Path $dir.FullName -File
Write-Host "Checking files in directory: $($dir.FullName)"
if ($files.Count -eq 0) {
Write-Host "No files found in directory: $($dir.FullName)"
} else {
Write-Host "$($files.Count) files found in directory: $($dir.FullName)"
}
# Initialize episode number
$episodeNumber = 1
foreach ($file in $files) {
Write-Host "Processing file: $($file.FullName)"
# Extract folder name without the "[*Series Name*]" part
$folderName = $dir.Name -replace "[*Series Name*][d+(,d+)*] ", ""
Write-Host "Extracted folder name: $folderName"
# Generate new file name
$newFileName = "{0} {1:D2}{2}" -f $folderName, $episodeNumber, $file.Extension
Write-Host "New file name: $newFileName"
# Generate new file path
$newFilePath = Join-Path -Path $dir.FullName -ChildPath $newFileName
Write-Host "New file path: $newFilePath"
Write-Host "Renaming '$($file.Name)' to '$($newFileName)'"
# Rename the file
Rename-Item -Path $file.FullName -NewName $newFilePath -Force
# Increment the episode number
$episodeNumber++
}
}
Write-Host "Script execution completed."
The script is mostly written by ChatGPT, but as far as I can tell it’s supposed to do exacly what I want it to do, rename all episodes to “Arc Name ##”, with incremental episode numbers.
No matter where and how I try to run it it only output the “No files found in directory: $($dir.FullName)” error, even when I’m 100% sure that I got media files there (both .mp4 and .mkv).
Is there anything obvious I’m missing? Or is there something wrong with my script?
I’ve tried to use ChatGPT for bugfixing, I’ve tried to move the directory to different drives, including a network drive, tried with PS’s ExecutionPolicy both in restricted and unrestricted mode, and with my terminal launched as administrator, but I still get the same result every time. I’ve also tried with both Windows Terminal, and PowerShell’s CLI directly.
Alexander Haarberg Qupva is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.