Home > OS >  Delete everything in a file name BEFORE the last occurrence of an Underscore in Powershell?
Delete everything in a file name BEFORE the last occurrence of an Underscore in Powershell?

Time:11-04

I have tens of thousands of files which will need to be renamed in large batches after being manually manipulated. All of the files will have a barcode followed by a unique identifying string of alphanumerics. They will all have the same .PDF extension as well. All files should have an underscore before the unique identifier.

For example: 12 44571 522110_10_E-354-98-U90368.ENG
or : 14 44571 500169_9_Monroe NE_G-462-02-5674.GER

What I need to keep after renaming these files is the unique identifier which looks like this:

 E-354-98-U90368.ENG
 G-462-02-5674.GER

I am not versed in Powershell and have found a 2-step process that works, but if there is an error in the file name, to begin with, it deletes the extension and the important unique identifier above.

The two-step process is this. 1st, get rid of the barcode and # after it for each file. If it does not have a name after this, then I'm done. If in the 2nd example, there is Monroe NE between the barcode and the unique identifier, I use the 2nd step.

How can I delete everything before the LAST occurrence of the Underscore in one step?

This is what I tried:

1st Step :

Get-ChildItem -File "Folder Path Name" | Rename-Item -NewName { $_.Name -replace "Barcode", "" }

2nd Step:

$Files = Get-ChildItem -Path 'Folder Path Name’ -File 
foreach ($File in $Files) {
  $Split = $File.Name -split '_'
  if ($Split.Count -gt 1) {
    Rename-Item -Path $File.FullName -NewName $Split[1]}}

CodePudding user response:

To get the last item in an array, use the index -1:

PS ~> $string = 'a_b_c'
PS ~> $split = $string -split '_'
PS ~> $split[-1]
c

CodePudding user response:

Along with 'Mathias R. Jessen's' helpful and succinct answer; here's another option to add to your arsenal of info.

'12 44571 522110_10_E-354-98-U90368.ENG', 
'14 44571 500169_9_Monroe NE_G-462-02-5674.GER' | 
ForEach-Object {$PSItem.Substring($PSItem.LastIndexOf('_') 1)}
# Results
<#
E-354-98-U90368.ENG
G-462-02-5674.GER
#>  
  • Related