Skip to content

Instantly share code, notes, and snippets.

@akamud
Forked from lucasteles/how-to.ps1
Created May 2, 2020 12:02
Show Gist options
  • Save akamud/7a90ae1ac03250c2d8d0b6525bd52a79 to your computer and use it in GitHub Desktop.
Save akamud/7a90ae1ac03250c2d8d0b6525bd52a79 to your computer and use it in GitHub Desktop.
Rename all file names and replace all files content
# copy the replace-everything.ps1 to the folder
# run
.\replace-everything.ps1 -Folder . -FilePattern *.cs -TextToChange "from" -NewText "To"
param(
[String] $Folder,
[String] $FilePattern,
[String] $TextToChange,
[String] $NewText
)
function Remove-Empty-Folders {
param($Path)
Get-ChildItem $Path -Recurse -Force -Directory |
Sort-Object -Property FullName -Descending |
Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } |
Remove-Item -Verbose
}
function _change-file-contents-and-rename {
param($Files)
foreach ($file in $Files)
{
if($file.PSPath -Match '.git') { continue }
if($file.PSPath -Match '.dll') { continue }
if (-Not ($file -is [System.IO.DirectoryInfo])) {
echo $("Changing: " + $file.name + " content..." )
(Get-Content $file.PSPath) | Foreach-Object { $_ -replace $TextToChange, $NewText } | Set-Content $file.PSPath
}
$newFile = $file.name -replace $TextToChange, $NewText
if ($file.name -ne $newFile) {
echo $("Changing: " + $file.name + " to " + $newFile)
Rename-Item -NewName $newFile -ErrorAction Stop $file
}
}
}
Remove-Empty-Folders -Path $Folder
$files = Get-ChildItem -Path $Folder -Recurse $FilePattern -File
_change-file-contents-and-rename -Files $files
$folders = Get-ChildItem -Path $Folder -Recurse -Directory
_change-file-contents-and-rename -Files $folders
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment