[Powershell] – renaming folders

Last day I wanted to have uniform folder names, some of the folders currently have a set of ‘[‘, ‘]’ chars containing dates and some additional info afterwards.
As this was not really necessary and only makes the name longer then needed I decided to rename them, of course using Powershell.
Initially I needed to collect a list of all items:

gci $pwd -recurse

But i was only interested in the folders, so a where clause is in order:

gci $pwd -recurse | where {$_.Mode -match "d"}

Now that we have a list of all folders, we can start with renaming them leaving all chars as from the first ‘[‘:
after a lot of struggling and my one liner not working  I turned to good all friend ‘Google’ and the solution was found on  Mike Ormond's Blog.
Let’s give it another spin:

gci $pwd | where {$_.Mode -match "d"} | move-item -dest { join-path $pwd ([regex]'\[(.*)').replace($_.Name, "")}

nevertheless i got a new error:

Move-Item : The process cannot access the file because it is being used by another process.
At line:1 char:50 gci $pwd | where {$_.Mode -match "d"} | move-item  <<<< -dest { join-path $pwd ([regex]'\[(.*)').replace($_.Name, "")}

but as i looked into my directory, all folders where renamed. so i decided to add the following switch:

-ea SilentlyContinue –ev errorlog

Bare in mind that it is not always wise to let Powershell continue on errors, but as it did the job for me…
the variable $errorlog still holds all errors encountered in the IO operation and can easily be outputted to the console screen or a file.
the PowerShell Team has a great blog entry on 'Managing non-terminating errors' .

Published Tuesday, February 02, 2010 5:08 PM by scallebaut
Filed under:

Comments

No Comments