Wednesday, August 3, 2011

Using PowerShell to do a find and replace on all files and subfolders

I looked around for a while and just couldn't find a script that did this for me. So here it is so I don't lose it. It was useful as part of setting up a new VS2010 project that was a complete copy of the one from another project.


$search = "SearchString"
$replace = "ReplaceString"

function RenameFile ($fileInfo)
{
if ($fileInfo.Name.Contains($search))
{
$newFullName = $fileInfo.DirectoryName + "\" + $fileInfo.Name.Replace($search, $replace)
Move-Item $fileInfo.FullName $newFullName

return 1
}
return 0
}

function RenameDirectory ($dirInfo)
{
if ($dirInfo.Name.Contains($search))
{
$newFullName = $dirInfo.Parent.FullName + "\" + $dirInfo.Name.Replace($search, $replace)
Move-Item $dirInfo.FullName $newFullName

return 1
}
return 0
}

$files = Get-ChildItem -Path . * -Recurse -Force

$i = 0
$j = 0

# Rename files
foreach ($file in $files)
{
if ($file.GetType().ToString() -eq "System.IO.FileInfo")
{
if (RenameFile($file) -eq 1)
{
$i = $i + 1
}
}
}

# Now rename directories
foreach ($file in $files)
{
if ($file.GetType().ToString() -eq "System.IO.DirectoryInfo")
{
if (RenameDirectory($file) -eq 1)
{
$j = $j + 1
}
}
}

Write-Host Renamed $i files, $j directories.

1 comment:

  1. finally... a script that helped me with my (stupid and simple) problem instead of half solutions telling me to encapsulate code here or there or fiddle a little blabla... Thanks!

    ReplyDelete