PowerShell to remove all letters and dashes leaving UPC

Viewed 39

I have about 1,800 .pdfs including a UPC with dashes and text that need to be removed to manage. I found a code to remove extra spaces and underscores.

How do I remove all text leaving just the UPCs?

01182232110_V1R1_CartonOL_KP_DNV15.pdf    

... to ...

01182232110.pdf
1 Answers
# Targets .pdf files in the current dir.
# Add a -LiteralPath / -Path argument to target a different dir.
# Add -Recurse to target .pdf files in the target dir's entire *subtree*.
Get-ChildItem -Filter *.pdf |
  Rename-Item -NewName {  $_.Name -replace '_.+(?=\.)' } -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

-replace '_.+(?=\.)' in essence removes all characters starting with the first _ from the input file's base name (preserving the extension).

Related