Your basic ITPro blog... What's going on at work, what I'm interested in.

Friday, June 20, 2008

2008-06-20 - PowerShell Exercise

In today's Hey, Scripting Guy!, we tackle file renaming. PowerShell is great at this sort of thing.

The Question:

Hey, Scripting Guy (and the $12 million-a-year Scripting Editor)! Is there a way to mass-rename all the files in a folder, changing the letter case as needed?
-- MV

This example converts all filenames to lower case.

The Scripting Guys' Answer

   1: strComputer = "."
   3: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
   5: Set colFileList = objWMIService.ExecQuery _
   6:     ("ASSOCIATORS OF {Win32_Directory.Name='C:\Test'} Where " _
   7:         & "ResultClass = CIM_DataFile")
   9: For Each objFile In colFileList
  10:     strName = LCase(objFile.FileName)
  11:     strExtension = LCase(objFile.Extension)
  13:     strNewName = objFile.Drive & objFile.Path & strName & "." & strExtension
  14:     objFile.Rename(strNewName)
  15: Next

My PowerShell Answer

dir | foreach {Rename-Item $_ -NewName $_.Name.ToLower()}

They had a second example that converted the first letter of each word to upper case. I didn't come up with a way to do this too much easier than the VB way... But then, I still tend to think of things in VB terms, which isn't too great when working in PowerShell. I am still working on changin' my ways of thinkin'


/\/\o\/\/ said...

You do not need the foreach, you can use a scriptblock for the NewName parameter.

dir | Rename-Item -NewName {$_.Name.ToLower()}

h.t.h. in thinking PoSH ;-)


Greetings /\/\o\/\/

/\/\o\/\/ said...


What do you think as this for an anwer the the second one ? :

dir | Rename-Item -NewName {(Get-Culture).TextInfo.ToTitleCase($}

Greetings /\/\o\/\/

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332