$text = "thIS is A TEST teXT" [CultureInfo]::InvariantCulture.TextInfo.ToTitleCase($text) Words that are ALL CAPITALIZED will remain untouched:
This Is A TEST Text
如果您不喜欢有些例外的单词没有被转成首字母大写,那么先将文本转为全小写然后传给该方法:
1 2 3 4 5
PS> [CultureInfo]::InvariantCulture.TextInfo.ToTitleCase('TEST remains aLL uppER Case') TEST Remains All Upper Case
PS> [CultureInfo]::InvariantCulture.TextInfo.ToTitleCase('TEST remains aLL uppER Case unless you lowerCASE YOUR text beFORE'.ToLower()) Test Remains All Upper Case Unless You Lowercase Your Text Before
$text = "thIS is A TEST teXT" # title convert and then replace two or more spaces with one space only: [CultureInfo]::InvariantCulture.TextInfo.ToTitleCase($text.ToLower()) -replace'\s{2,}', ' ' Now this approach returns the exact same result as in our previous parts:
process { [CultureInfo]::InvariantCulture.TextInfo.ToTitleCase($text.ToLower()) -replace'\s{2,}', ' ' } }
当您运行该函数,它将和之前的版本一样灵活和可扩展:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# you get automatic prompts when you forget to submit mandatory arguments: PS> Convert-CapitalizeWord cmdlet Convert-CapitalizeWord at command pipeline position 1 Supply values for the following parameters: Text: heLLO WOrld Hello World
# you can submit your text to the -Text parameter: PS> Convert-CapitalizeWord-Text'this iS a LONG teXT' This Is A Long Text
# you can pipe as many texts as you like (scalable) via the pipeline: PS> 'Hello world!', 'someTHING else' | Convert-CapitalizeWord Hello World! Something Else
$text = "thIS is A TEST teXT" # split text in words $words = $text-split'\s{1,}' | # use ForEach-Object to break down the problem to solving ONE instance of your problem # regardless of how many words there are, the following script block deals with # one word at a time: ForEach-Object { $theWord = $_ # use .NET string methods on the object to solve your issue: $theWord.SubString(0,1).toUpper() + $theWord.SubString(1).ToLower() }
# the result is a string array. Use the -join operator to turn it into ONE string: $result = $words-join' ' $result
$text = "thIS is A TEST teXT" # split text in words $words = $text-split'\s{1,}' | # use ForEach-Object to break down the problem to solving ONE instance of your problem # regardless of how many words there are, the following script block deals with # one word at a time: ForEach-Object { $theWord = $_ # use .NET string methods on the object to solve your issue: $theWord.SubString(0,1).toUpper() + $theWord.SubString(1).ToLower() }
# the result is a string array. Use the -join operator to turn it into ONE string: $result = $words-join' ' $result
By assigning the enum type [ServerTypes] to your result variable, all translating is performed automatically, and cryptic code numbers now show as friendly text. 通过将枚举类型 [ServerTypes] 绑定到您的结果变量,所有转换都会自动进行,而且现在幻数可以转换为友好的文本。