-2

I need help with replacing file names before underscore with nothing.

Ex: ABC_123.xls and I want it to rename to 123.xls and CAB_234.xls to 234.xls.

2
  • If you don't find a powershell solution, I have a program I wrote many years ago, specifically for bulk renaming files on windows. Commented Oct 11, 2022 at 21:42
  • Welcome to SU. How to ask. SuperUser / Stackoverflow are not script-writing services. Anyway, this is very simple to do and very common, there are many blogs, documents, and examples all over the web. There are PowerShell cmdlets for this. Get-Help -Name Get-ChildItem -Details and Get-Help -Name Get-ChildItem -Example, then Get-Help -Name Rename-Item -Details and Get-Help -Name Rename-Item -Examples. You simply use a RegEx replace to get rid of what you want. Do a search for PS string replacement on the web. Commented Oct 12, 2022 at 0:56

1 Answer 1

2

As per my comment, this is literally one line of code to accomplish this task.

You must submit code (show your effort) for folks to want to help you, but I am putting this here as a launch point to get you in the right direction. Many Youtube videos show you how to do this and more. Search Youtube for 'Beginning PowerShell' or 'PowerShell file and folder management'.

Basic/simple string replacement:

# Replace the start of a string up to and including the underscore. https://regex101.com
'ABC_123.xls', 'CAB_234.xls' -replace '.*_'
# Results
<#
123.xls
234.xls
#>

Create test files:

'ABC_123.xls', 'CAB_234.xls' | 
ForEach-Object {New-Item -Path 'D:\Temp' -Name $PSItem -ItemType File}
# Results
<#
    Directory: D:\Temp


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         11-Oct-22     18:14              0 ABC_123.xls
-a----         11-Oct-22     18:14              0 CAB_234.xls
#>

Get a list of files by full name and change it:

(Get-ChildItem -Path 'D:\Temp' -Filter '*.xls').FullName | 
ForEach-Object { Rename-Item -Path $PSItem -NewName ($PSItem -replace '.*_') -WhatIf}
# Results
<#
What if: Performing the operation "Rename File" on target "Item: D:\Temp\ABC_123.xls Destination: D:\Temp\123.xls".
What if: Performing the operation "Rename File" on target "Item: D:\Temp\CAB_234.xls Destination: D:\Temp\234.xls".
#>

Remove the WhatIf to make it real.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.