Wednesday, April 29, 2009

Powershell Rename-Item vs Copy-Item: Changing file names to upper case

I needed recursively change all file and sub-directory names in a directory from mixed case to upper case. To me, this felt like a problem for PowerShell, but maybe I was wrong. Here was my first attempt:



Get-ChildItem -Recurse -Path "C:\media" | % {Rename-Item $_.FullName -NewName ([string]$_.Name).ToUpper()};


However, I received the following error:


Rename-Item : Source and destination path must be different.


So it looks like PowerShell refused to rename file1 to FILE1, because it thinks that they are the same file. In order to get around this I ended up copying the entire tree, and even that command isn't particularly elegant:


Get-ChildItem -Recurse -Path "C:\media" | % {Copy-Item -Force $_.FullName ([string]$_.FullName).Replace("C:\media", "C:\MEDIA2").ToUpper()};


If there is a better way to do this, I'd love to know.

No comments: