Most people know how to convert a string to all upper case or all lower case. In this quick tip, I’ll show you how to use ‘TextInfo’ to convert a string to Title Case.
$string = 'test string' [System.Threading.Thread]::CurrentThread.CurrentCulture.TextInfo.ToTitleCase($string)
As you see if you test it out your self, it will output ‘Test String’. The ToTitleCase method will capitalize all words in the string.
If, on the other hand, you would like to only capitalize the first word in a sentence, the following small function might come in handy:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Out-CapitalizedString { | |
param([string]$String) | |
if(-not([System.String]::IsNullOrEmpty($String))) { | |
foreach ($sentence in ($String.Split('.'))) { | |
if(-not([System.String]::IsNullOrEmpty($sentence))) { | |
$sentence = $sentence.Trim() | |
[array]$outputString += [char]::ToUpper($sentence[0]) + $sentence.Substring(1) | |
} | |
else { | |
[array]$outputString += $sentence | |
} | |
} | |
Write-Output ($outputString -join '. ').Trim() | |
} | |
} |
You can also use:
$host.CurrentCulture.TextInfo.ToTitleCase($string)
LikeLike
Thanks Greg. That’s even easier 🙂
LikeLike