Last active
May 2, 2020 12:02
-
-
Save lucasteles/ebdafa9e416e21b997ec75e601d5abc5 to your computer and use it in GitHub Desktop.
Rename all file names and replace all files content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# copy the replace-everything.ps1 to the folder | |
# run | |
.\replace-everything.ps1 -Folder . -FilePattern *.cs -TextToChange "from" -NewText "To" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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