Oct 8, 2015

Rename all files replacing a text using PowerShell

Let's say you have a number of files at location C:\demo with text "OldValue" in it. And you want to replace text "OldValue" to "NewValue" in all files. To do that follow the steps below:

  1. Open Windows PowerShell.
  2. Navigate to location C:\demo
  3. Run the following Windows PowerShell command: 
    Get-ChildItem -Filter "*OldValue*" -Recurse | Rename-Item -NewName {$_.name -replace 'OldValue','NewValue' }
  4. All files will be renamed.

  • The command Get-ChildItem -Filter "*OldValue*" finds all files with the string "OldValue" anywhere in the name.
  • Get-ChildItem searches recursively through all subfolders.
  • | (the pipe character) instructs Windows PowerShell to take each item (object) found with the first command (Get-ChildItem) and pass it to the second command (Rename-Item)
  • Rename-Item renames files and other objects.
  • {$_.name -replace 'OldValue','NewValue' } instructs Rename-Item to find the string "OldValue" in the file name and replace it with "NewValue"

No comments: