通过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
-WhatIfflag will output every intended rename without actually modifying files. Run it once to make sure the new filenames look right, then remove-WhatIfto apply changes. - Target Specific Files: If you only want to rename, say, Excel files, add
-Filter "*.xlsx"to theGet-ChildItemcommand. - 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
-Fileflag inGet-ChildItemprevents this) - Forgetting to handle files with no underscores, leading to empty filenames
内容的提问来源于stack exchange,提问作者bbcompent1
相关产品推荐
相关产品推荐

