You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the D:\rename directory recursively for all .mp4 and .mkv files.
  • -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 like filename123_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:36:02