Search code examples
powershellcmdwindows-7-x64

windows 7 find and replace string in files and folders


In windows powershell ISE i'm trying to replace a string in a lot of files name and folders name example i have files and folders like

foo_file1.txt
file2_foo.php
file3_foo_file.js
foo/folder1/file.ext
folder2/file4_foo.doc
foo_folder/file5.ppt
folder/foo/file_foo.jpg

I want to change all "foo" to "bar" for example. I used windows powershell command

$dir = "the Path of folder Parent"
CD $dir
Get-Childitem -recurse | 
Where-Object {$_.Name -match "foo"}
rename-item -NewName { $_.Name -replace "foo", "bar" }

but this command is not working


Solution

  • Get-Childitem -recurse | Where-Object {$_.Name -match "foo"} | % {  Rename-Item -NewName ( $_.Name -replace "foo", "bar" ) -Path $_.FullName }
    

    Seems that you forgot the -Path parameter of Rename-ITem.

    Hope that helps.