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

通过PowerShell脚本批量移除文件名最后一个下划线及前缀内容

Got it, let's get this sorted for you! The core task here is stripping everything up to and including the last underscore in your filenames so you're left with just the ERP-matching part number. Below is a tested PowerShell script that handles this reliably, plus breakdowns to help you tweak it to your needs:

PowerShell Script to Rename Files (Keep Text After Last Underscore)
# Replace this with your actual folder path
$targetDirectory = "C:\Path\To\Your\Files"

# Grab all files in the target directory (add -Filter if you need specific file types)
Get-ChildItem -Path $targetDirectory -File | ForEach-Object {
    # Split the filename (without extension) into parts using underscores as separators
    $nameSegments = $_.BaseName -split '_'

    # If there's at least one underscore, take the final segment; else keep the original name
    $newBaseName = if ($nameSegments.Count -gt 1) { $nameSegments[-1] } else { $_.BaseName }

    # Combine the new base name with the original file extension
    $newFileName = "$newBaseName$($_.Extension)"

    # Preview changes first with -WhatIf! Remove it once you're ready to apply renames
    Rename-Item -Path $_.FullName -NewName $newFileName -WhatIf
}

Key Details & Tips:

  • Test First: The -WhatIf flag will output every intended rename without actually modifying files. Run it once to make sure the new filenames look right, then remove -WhatIf to apply changes.
  • Target Specific Files: If you only want to rename, say, Excel files, add -Filter "*.xlsx" to the Get-ChildItem command.
  • Edge Case Safety: Files with no underscores will keep their original names—no broken filenames here.
  • Permissions: Make sure you have write access to the target directory; if you get errors, run PowerShell as Administrator.

Why Your Original Script Might Have Failed:

Common pitfalls that break these kinds of rename scripts:

  • Not accounting for multiple underscores (e.g., using $nameSegments[1] instead of $nameSegments[-1] to get the last part)
  • Losing the file extension by only renaming the base name without appending $_.Extension
  • Accidentally including folders in the operation (the -File flag in Get-ChildItem prevents this)
  • Forgetting to handle files with no underscores, leading to empty filenames

内容的提问来源于stack exchange,提问作者bbcompent1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:13:47