Skip to content

Commit

Permalink
final fix of rename script
Browse files Browse the repository at this point in the history
  • Loading branch information
jurczewski committed Jun 30, 2024
1 parent 493af34 commit 67edde0
Showing 1 changed file with 15 additions and 24 deletions.
39 changes: 15 additions & 24 deletions rename-all.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# Function to replace "ProjectName" in file and directory names and their content with the given phrase
function Replace-FilenameAndContent {
param (
[string]$NewPhrase
Expand All @@ -8,41 +7,33 @@ function Replace-FilenameAndContent {
$Directory = Get-Location

# Get all files and directories in the current directory and subdirectories
$items = Get-ChildItem -Path $Directory -Recurse
$items = Get-ChildItem -Path $Directory -Recurse | Where-Object {
-not $_.PSIsContainer -and
$_.Name -notlike "README.md" -and
$_.Name -notlike "rename-all.ps1"
}

# First, replace "ProjectName" with the new phrase in file content
$files = $items | Where-Object { -not $_.PSIsContainer }
foreach ($file in $files) {
# Replace "ProjectName" with the new phrase in file content
foreach ($file in $items) {
try {
$content = Get-Content -Path $file.FullName -ErrorAction Stop
$newContent = $content -replace "ProjectName", $NewPhrase
Set-Content -Path $file.FullName -Value $newContent
Write-Host "Replaced content in '$($file.Name)'"
Write-Host "Replaced content in '$($file.FullName)'"
}
catch {
Write-Warning "Could not read or write content of '$($file.FullName)'. Skipping content replacement."
}
}

# Then, rename directories and files
$directories = $items | Where-Object { $_.PSIsContainer } | Sort-Object -Property FullName -Descending
foreach ($directory in $directories) {
if ($directory.Name -like "*ProjectName*") {
$newDirName = $directory.Name -replace "ProjectName", $NewPhrase
$newDirPath = Join-Path -Path $directory.Parent.FullName -ChildPath $newDirName

Rename-Item -Path $directory.FullName -NewName $newDirPath
Write-Host "Renamed directory '$($directory.FullName)' to '$($newDirPath)'"
}
}

foreach ($file in $files) {
if ($file.Name -like "*ProjectName*") {
$newFileName = $file.Name -replace "ProjectName", $NewPhrase
$newFilePath = Join-Path -Path $file.DirectoryName -ChildPath $newFileName
# Rename directories and files
foreach ($item in $items) {
if ($item.Name -like "*ProjectName*") {
$newName = $item.Name -replace "ProjectName", $NewPhrase
$newPath = Join-Path -Path $item.DirectoryName -ChildPath $newName

Rename-Item -Path $file.FullName -NewName $newFilePath
Write-Host "Renamed file '$($file.FullName)' to '$($newFilePath)'"
Rename-Item -Path $item.FullName -NewName $newPath -Force
Write-Host "Renamed '$($item.FullName)' to '$($newPath)'"
}
}
}
Expand Down

0 comments on commit 67edde0

Please sign in to comment.