Rename Files With Keyword

How do I rename .txt file of a certain keyword ? For example, any file with word TEXT anywhere in its name will be renamed as TEXT

Get-ChildItem "C:\Folder" -Filter *.txt -recurse | Rename-Item -NewName { $_.Name -replace '*TEXT*.txt','TEXT'.txt }
  1. What’s wrong with the code you shared?
  2. Don’t you want to keep the file extension?
  3. If there is more than one file in one folder you have to come up with a solution. :wink: :point_up:t3:

it gave this error when script ran.

Rename-Item : The input to the script block for parameter 'NewName' failed. The regular expression pattern '*TEXT*'.txt is not valid.

Each subfolder only has 1 file with a specific keyword, so there will be no accidental same names.

That’s the root cause. In regular expressions the asterisk (*) has a special meaning. So if you want to find something with the pattern text in it and you want to include what’s before and after you have to use regex syntax. So your new name script block should be something like this:

Get-ChildItem -Path . -Filter *.txt -Recurse | 
  Rename-Item -NewName {($_.BaseName -replace '.*text.*','TEXT') + $_.Extension}

Or … if you want to have it simpler …

Get-ChildItem -Path . -Filter *.txt -Recurse | 
    Rename-Item -NewName { $_.Name -replace '.*text.*\.txt','TEXT.txt' }

If you want to learn more about regex I’d recommend to digg deeper starting with this site: