Powershell command for removing text from filename across multiple files

Welcome Forums General PowerShell Q&A Powershell command for removing text from filename across multiple files

Viewing 3 reply threads
  • Author
    Posts
    • #203075
      Participant
      Topics: 1
      Replies: 1
      Points: 13
      Rank: Member

      I found a video online that showed me the following command:

      get-childitem *.pdf | foreach {rename-item $_ $_.name.replace(“text here”,””)}

      This worked for me but I am wondering if there is a way I can run it and remove text before and after stuff and how to do it.   Our file names come in from our vendor in this format:

      TA-G01-004-Q-G-A091020.pdf

      I want to remove everything and keep only the 01-004-Q in the middle but that number will be different per file name as well as the 091020 number.  Im not quite sure how to put in the wild card in order to put maybe the first or second number and let it find the rest before the .pdf extension.

      Secondly, is there a way I can write this into a batch file to where all I need to do is copy the files into that folder and run the file to rename everything?

    • #203078
      Participant
      Topics: 1
      Replies: 1
      Points: 13
      Rank: Member

      I will also want to add after Q a _FEB 2020(changing per month) so the final will just be “01-004-Q_FEB 2020.pdf”

    • #203081
      Participant
      Topics: 5
      Replies: 2368
      Points: 5,986
      Helping Hand
      Rank: Community MVP

      Assumed you always want to remove the first 4 charachters and keep the following 8 you can use the substring method like this:

      Get-ChildItem -Filter *.pdf -File | 
      ForEach-Object {
          Rename-Item -Path $_.FullName -NewName ($_.BaseName.substring(4, 8) + $_.Extension)
      }
    • #203093
      Participant
      Topics: 5
      Replies: 323
      Points: 470
      Helping Hand
      Rank: Contributor

      Assuming the part you want always starts with a single letter

      # Get part of filename then add date to said part
      Get-ChildItem -Filter *.pdf | ForEach-Object {
      $_.Name -match '\w(\d+-\d+-\w)' | Out-Null
      $date = get-date -Format "MMM yyy"
      
      # Use format operator to form new filename
      $newname = "{0}_{1}{2}" -f $Matches[1],$date,$_.Extension
      Rename-Item -Path $_.FullName -NewName $newname -Verbose
      }
      
Viewing 3 reply threads
  • The topic ‘Powershell command for removing text from filename across multiple files’ is closed to new replies.