Search code examples
powershell

Powershell- Getting a strange error when I try to replace characters in folder names


I often have .pdf files where I need to remove '- copy', or replace the date on all of them, etc. So I've been using a script to do so. I'm now trying to expand upon my current script to do the same thing ONLY to folders in a given directory, but I'm getting an error on anything that doesn't contain the characters I want to remove/change.

This is the script I currently use for .pdfs, in this example I just want to remove ABC from everything (i.e. replace it with nothing):

$path = "C:\examplepath"
$filter = '*.pdf'
get-childitem -path $path -filter $filter | 
 rename-item -newname {$_.name -replace 'ABC',''}

And this is what I've come up with to do the same, but only on folders (including subfolders):

$FolderPath = "C:\examplepath"

Get-ChildItem -Path $FolderPath -Directory -Recurse | rename-item -newname {$_.name -replace 'ABC',''}

It removes ABC from any folder names, but I get the following error for any folders that don't contain ABC. In this example, the folder was just named '1':

rename-item : Source and destination path must be different.
At line:3 char:55
+ ... Directory -Recurse | rename-item -newname {$_.name -replace 'ABC',''}
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\examplepath\1:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

I kind of understand what it's saying by 'source and destination path must be different'- it can't change a folder named '1' to a folder named '1'. But I don't understand why I'm getting that error now, but not when I run my .pdf script. It's not the end of the world since the script does what I want, but I'd be more comfortable if it wasn't returning errors.


Solution

  • Use a filter to ensure you're renaming a folder that does have ABC in its name. You should also probably consider start renaming them from the deepest in hierarchy, so Sort-Object on FullName:

    $FolderPath = 'C:\examplepath'
    Get-ChildItem -Path $FolderPath -Directory -Recurse |
        Where-Object Name -Like *ABC* |
        Sort-Object FullName -Descending |
        Rename-Item -NewName { $_.Name -replace 'ABC' }
    

    As for the error, reason is that if you rename a file using its same name it isn't an issue but for a directory it's different, it must have a different name, thus the need for a filter, that's how the underlying .NET APIs work when renaming.