Forum Discussion
Powershell Clean up Folder Names - Rename Folders and Subfolders Recursively
Hi friends,
I hope I have posted this in the correct forum.
I am trying to rename folders and subfolders.
I am cleaning up the folders names first removing junk spaces and things I don’t want.
I am really stuck on renaming the folders.
However I may be making some newbie mistakes
After looking at this code all day I have code blindness.
Various tests gave me these types of errors
Folder doesn’t exists
Access denied
Source and destination must be different
$Source_Folder='C:\Users\Dan\Desktop\Test'
$folders = Get-ChildItem -Directory -Recurse $Source_Folder
#$folders # display on screen
Foreach ($folder in $folders)
{
$new_folder_name = $folder.Name
# Remove Characters
$new_folder_name = $new_folder_name -replace '#', ' '
# Remove Hyphen with _
$new_folder_name = $new_folder_name -replace '-', '_'
# and some more replacesments......
# Rename the Folders
$new_folder_path = ($folder.DirectoryName + "\" + $new_folder_name)
Write-Host "Renaming:" $folder.FullName "to" $new_folder_path
Rename-Item $folder.FullName $new_folder_path
}
Please may some one point me in the right direction
Thank you so much
Dan_CS It's the special characters, if you replace @ with at for example, it does work for me
$Source_Folder = 'd:\temp\Test' $folders = Get-ChildItem -LiteralPath $Source_Folder -Directory Foreach ($folder in $folders) { $new_folder_name = $folder.Name # Remove Characters $new_folder_name = $new_folder_name -replace '#', ' ' # Remove Hyphen with _ $new_folder_name = $new_folder_name -replace '-', '_' # Remove @ with at $new_folder_name = $new_folder_name -replace '@', 'at' # and some more replacements...... Write-Host "Renaming:" $folder.FullName "to" $new_folder_name Rename-Item "$($folder.FullName)" "$($new_folder_name)" -Verbose }
10 Replies
Dan_CS I changed it a little for you, the target path shouldn't be in full name, just the directory name
$Source_Folder = 'd:\temp\Test' $folders = Get-ChildItem -Directory -Recurse $Source_Folder Foreach ($folder in $folders) { $new_folder_name = $folder.Name # Remove Characters $new_folder_name = $new_folder_name -replace '#', ' ' # Remove Hyphen with _ $new_folder_name = $new_folder_name -replace '-', '_' # and some more replacements...... Write-Host "Renaming:" $folder.FullName "to" $new_folder_name Rename-Item "$($folder.FullName)" "$($new_folder_name)" }- Dan_CSCopper Contributor
Hello Harm,thank you for your help.
It did rename some folders but some I get errors like below
Rename-Item : Source and destination path must be different.
At C:\Users\Dan\Desktop\FORUM Folder.ps1:44 char:5
+ Rename-Item $($folder.FullName) $($new_folder_name)
Also another error folder does not exist.I will keep trying and testing
Thank you
- Ok, but what is the source en destination at that moment? What's the output from line 14? (Write-Host "Renaming"...