I have a folder that has 100s of subfolders and files within those subfolders that have names with leading and trailing spaces. These folders and files were created using a Node JS app. I need to now remove the leading and trailing spaces from the file names of the folders and files.
I found this script which seems to be built for this purpose.
If I use the function to create files/folders with leading spaces mentioned on the same blog, the script is able to rename those.
However, it does not work with files/folders created using the node JS app. When renaming the folder/file, it fails with -
Rename-Item : Cannot rename because item at 'C:\Folder\ Example App Folder ' does not exist.
At C:\renamefileswithspaces.ps1:25 char:13
+ Rename-Item -LiteralPath $_.fullname -NewName (“{0}{1}{2} ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
If I run the following cmdlets for just one folder (outside the script), it fails with the same error -
$f = Get-ChildItem -Path 'C:\Folder' -Filter "*Example*"
Rename-Item -LiteralPath $f.FullName -NewName $f.Name.Trim()
Rename-Item : Cannot rename because item at 'C:\Folder\ Example App Folder ' does not exist.
At line:1 char:1
+ Rename-Item -LiteralPath $f.FullName -NewName $f.Name.Trim()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Why does Rename-Item fail for files/folders created using the app whereas it works for files/folders created using PowerShell?
Edit: Running on Windows Server 2016 Standard. PowerShell version - 5.1.14393.3866
Edit 2: Updated to PowerShell 7.1.4 from here and the issue still exists.