2

I have many folders with many files in each that I want to capitalize the first letter of each word for in a batch. I've seen solutions for capitalizing strings, but that's not what I'm after. I use Powershell and I like to copy the script into the active folder and just run it. Therefore, most of my PS scripts begin with:

$PSScriptRoot

Example to rename files:

$PSScriptRoot
Get-ChildItem -File | Rename-Item -NewName { $_.Name -Replace "OLD","NEW"}

So just looking for something similar that capitalizes the first letter of each word in ALL filenames (excluding the extensions of course) in a batch.

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    Is there a common character separating each word? – Doug Maurer Dec 01 '20 at 00:37
  • 1
    Like this? https://stackoverflow.com/questions/22694582/capitalize-the-first-letter-of-each-word-in-a-filename-with-powershell – jfrmilner Dec 01 '20 at 00:56
  • embedding spaces [or other non-standard chars] in file_names/parameter_names/property_names ... or anything that will require quotes to use ... is unwise. if you can, avoid the whole idea. if you cannot avoid the idea, use underscores instead of spaces. – Lee_Dailey Dec 01 '20 at 01:05
  • 1. Thank you Mathias for help with the edit. 2. Hi Doug, only common character would be a space between words but that won't apply to single word filenames or the first word in a multiple name file. 3.Hi jfrmilner, yes I saw that post but it appears to be for strings that you have to copy/paste into the script and not an auto-batch solution for hundreds of files (unless I've missed something). – Karen Strong Dec 01 '20 at 01:33

1 Answers1

3

Something like this?

Get-ChildItem -File | Rename-Item -NewName { "{0}{1}" -f ( Get-Culture ).TextInfo.ToTitleCase( $_.BaseName.ToLower() ), $_.Extension}

for better performance you can rename only file with difference name like this :

Get-ChildItem -File | select *, @{N="NewName";E={"{0}{1}" -f ( Get-Culture ).TextInfo.ToTitleCase( $_.BaseName.ToLower() ), $_.Extension}} | 
where {$_.Name -CNE $_.NewName} | Rename-Item -NewName {$_.NewName}
Esperento57
  • 16,521
  • 3
  • 39
  • 45
  • 1
    Wouldn't ToTitleCase change all words to title case? As in, if a file name is "this is my file.txt" wouldn't this change it to "This Is My File.txt"? EDIT: Sorry, did not see that OP asked for that specifically, I misinterpreted it as "only the first word". – Tanaka Saito Dec 01 '20 at 02:19
  • Esperento57 - both solutions work perfectly and are exactly what I was looking for. Thank you so much. Also, thank you to everyone else who offered suggestions and solutions. – Karen Strong Dec 01 '20 at 20:28