PowerShell实现按目录名重命名文件并截断指定字符串后内容
Rename Files to Truncated Directory Names (Remove "Release" and Beyond)
Here's a complete PowerShell script that accomplishes exactly what you need—renaming your video files to match their parent directory name, but truncating everything from the word "Release" (and any characters after it) while preserving the original file extension.
Complete Script
Get-ChildItem D:\rename -Include *.mp4,*.mkv -Recurse | Rename-Item -NewName { # Split directory name at the first occurrence of "Release" and take the first part $truncatedName = $_.Directory.Name -split 'Release', 2 | Select-Object -First 1 # Clean up trailing underscores/spaces left from the truncation $cleanedName = $truncatedName.TrimEnd('_', ' ') # Combine cleaned name with original file extension "$cleanedName$($_.Extension)" } -WhatIf # Remove this flag when you're ready to apply the renames
How It Works
Let's break down the key parts of the script:
Get-ChildItem: Scans theD:\renamedirectory recursively for all.mp4and.mkvfiles.-split 'Release', 2: Splits the parent directory name into two parts at the first instance of "Release"—we only keep the first part (everything before "Release").TrimEnd('_', ' '): Cleans up any leftover trailing characters like underscores or spaces (common in directory names likefilename123_Release v.1)."$cleanedName$($_.Extension)": Merges the cleaned directory name with the original file extension to form the new filename.-WhatIf: A safe mode flag that previews all renames without making changes. Remove this once you verify the preview looks correct.
Example Output
- Directory name:
filename123_Release v.1 - Original filename:
myvideo.mp4 - New filename:
filename123.mp4
Notes
- If your target truncation string isn't "Release", just replace
'Release'in the script with your specific substring (e.g.,'Version'). - Be cautious of duplicate filenames: if two different directories truncate to the same name, the script will throw an error when trying to rename files to the same name in the same location. You can add logic to handle duplicates (like appending a number) if needed, but that's an extra step.
内容的提问来源于stack exchange,提问作者Gary Quiring
相关产品推荐
相关产品推荐

