Capitalize the first letter of each word in a filename with powershell

梦想的初衷 提交于 2020-04-29 08:01:18

问题


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.


回答1:


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 }



回答2:


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.



来源:https://stackoverflow.com/questions/22694582/capitalize-the-first-letter-of-each-word-in-a-filename-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!