Skip to content

Instantly share code, notes, and snippets.

@B0yma
Last active June 5, 2023 18:39
Show Gist options
  • Save B0yma/ec25893cec028f115147f9e2b85318f2 to your computer and use it in GitHub Desktop.
Save B0yma/ec25893cec028f115147f9e2b85318f2 to your computer and use it in GitHub Desktop.
script for powershell to rename
# This script works by using the Get-ChildItem cmdlet to recursively search for all files and folders in the target directory. For each item, it checks whether its name contains the search string. If it does, it constructs the new name by replacing the search string with the replace string, and then renames the item using the Rename-Item cmdlet.
# Note that we're using the ToLower() method to convert the item name to lowercase before checking for the search string. This ensures that we catch variations of the search string that are spelled with different capitalization.
# Again, you should use this script with caution, especially when renaming directories that contain files, as it can cause issues with file paths and dependencies.
# To run this PowerShell script, save it with a .ps1 extension (e.g., rename_comments.ps1) and execute it from a PowerShell prompt by entering the file path, e.g.: .\rename_comments.ps1. You will then be prompted to enter the target directory path.
$searchString = "string1"
$replaceString = "string2"
$targetDir = Read-Host "Enter the target directory path"
Get-ChildItem -Path $targetDir -Recurse | ForEach-Object {
# Rename file if it contains the search string
if ($_.Name.ToLower().Contains($searchString)) {
$newName = $_.Name.ToLower().Replace($searchString, $replaceString)
Rename-Item $_.FullName $newName -Force
}
# Rename folder if it contains the search string
if ($_.PSIsContainer -and $_.Name.ToLower().Contains($searchString)) {
$newName = $_.Name.ToLower().Replace($searchString, $replaceString)
Rename-Item $_.FullName $newName -Force
}
}
Write-Host "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment