27

I want to change the names of some files automatically.

With this code I change the lowercase letters to uppercase:

get-childitem *.mp3 | foreach { if ($.Name -cne $.Name.ToUpper()) { ren $.FullName $.Name.ToUpper() } }

But I only want the first letter of each word to be uppercase.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Gilko
  • 2,280
  • 8
  • 36
  • 45

4 Answers4

63

You can use ToTitleCase Method:

$TextInfo = (Get-Culture).TextInfo
$TextInfo.ToTitleCase("one two three")

outputs

One Two Three

$TextInfo = (Get-Culture).TextInfo
get-childitem *.mp3 | foreach { $NewName = $TextInfo.ToTitleCase($_); ren $_.FullName $NewName }
Bakudan
  • 19,134
  • 9
  • 53
  • 73
Klark
  • 8,162
  • 3
  • 37
  • 61
8

My answer is very similar, but I wanted to provide a one-line solution. This also forces the text to lowercase before forcing title case. (otherwise, only the first letter is effected)

$text = 'one TWO thrEE'
( Get-Culture ).TextInfo.ToTitleCase( $text.ToLower() )

Output:

One Two Three

Rob Traynere
  • 585
  • 1
  • 7
  • 14
  • If anyone knows how to do this by instantiating an enum method, PLEASE let me know. ie: [TextInfo]::ToTitleCase($text) – Rob Traynere Jun 03 '20 at 22:15
  • 1
    You don't have to lowerise. I tried in PS v5.1 and it converts "rEStarT" to "Restart" without `ToLower` call. – IgorStack Nov 02 '22 at 01:39
4

Yup, it's built into Get-Culture.

gci *.mp3|%{
    $NewName = (Get-Culture).TextInfo.ToTitleCase($_.Name)
    $NewFullName = join-path $_.directory -child $NewName
    $_.MoveTo($NewFullName)
}

Yeah, it could be shortened to one line, but it gets really long and is harder to read.

TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
2

There you go

[cultureinfo]::GetCultureInfo("en-US").TextInfo.ToTitleCase("what is my name?")
JonC
  • 978
  • 2
  • 7
  • 28
Fatman
  • 21
  • 2
  • 1
    thanks a ton! also recommend modifying the text with .ToLower() like "whAT IS my NAME?".ToLower(), or else it will not convert to Title Case if all letters in the word are capitalized. – Rob Traynere Oct 14 '20 at 16:12