Today I was faced with a slightly unusual issue where a bug in some 3rd party software meant that strings in all upper case weren’t being displayed in searches, although they were in the data view when you scrolled down the list. They couldn’t be changed to all lower case because that would change the semantics, so I was looking to quickly change them to Proper Case, or Title Case, or Start Case, however you feel it is best defined.
I knew that the String class had methods to change case to upper or lower, and I knew that I could convert my string to a char array, but I was pretty certain that there must be a one stop shop to achieve it quicker than that, and I was right.
After a quick Bing (yes, really), I found the System.Globalization.TextInfo class which has a ToTitleCase method, which makes it as simple as
(Get-Culture).TextInfo.ToTitleCase("this is my string")
to get “This Is My String”.
However, there was a pitfall with this; the ToTitleCase method has a “feature” which means that it leaves all-upper-case strings untouched, so
(Get-Culture).TextInfo.ToTitleCase("THIS IS MY STRING")
results in “THIS IS MY STRING”, rather than the desired “This Is My String”. Disaster! This is exactly that I was trying to get away from. What’s a scripter to do?!
(Get-Culture).TextInfo.ToTitleCase("THIS IS MY STRING".ToLower())
or in my particular script’s case “$(Get-Culture).TextInfo.ToTitleCase($_.name.ToLower()))”
Now I don’t especially care about it in this instance because the script is very specific to one thing at work, but the nice thing about using the ToTitleCase, and the reason that it’s not a standard String method, is that it’s culturally aware – so if you’re writing a script that may be used in a different culture elsewhere in the world where they use upper and lower case differently*, it should still do the right thing.
* I have no idea where, or how.