Skip to content

Instantly share code, notes, and snippets.

@aimtiaz11
Last active September 17, 2023 02:20
Show Gist options
  • Save aimtiaz11/31c1be50d6a3e71f3ccdb3f15556f03d to your computer and use it in GitHub Desktop.
Save aimtiaz11/31c1be50d6a3e71f3ccdb3f15556f03d to your computer and use it in GitHub Desktop.
Powershell - Replace occurance of a word in all files and directories under a parent directory
### DO A DRY RUN AND VERIFY BY COMMENTING OUT LINE 29 BEFORE UNCOMMENTING AND DOING PROPER RUN
### LINE TO COMMENT FOR DRY RUN: --> Rename-Item -Path $item.FullName -NewName $newName
###
## LICENSE MIT
# Define the root directory where you want to rename occurrences of the word
# IMPORTANT: CAREFULLY SET THIS. Otherwise it can have unintended consequences!!!
$rootDirectory = "C:\Users\123\git-repos\my-git-project"
# Define the word you want to replace and the replacement word
$oldWord = "wrong-name"
$newWord = "correct-name"
# Recursively search for files and directories in the root directory
$items = Get-ChildItem -Path $rootDirectory -Recurse
# Loop through each item (file or directory) and rename if necessary
foreach ($item in $items) {
# Check if the item's name contains the old word
if ($item.Name -match $oldWord) {
# Generate the new name by replacing the old word with the new word
$newName = $item.Name -replace $oldWord, $newWord
# Get the full path of the item's parent directory
$parentDirectory = $item.DirectoryName
# Construct the full path of the new item location
$newPath = Join-Path -Path $parentDirectory -ChildPath $newName
# Rename the item (file or directory)
Rename-Item -Path $item.FullName -NewName $newName
# Output the renaming action to the console
Write-Host "Renamed: $($item.FullName) -> $($newPath)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment