Converting a string to Proper Case in PowerShell

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.

Visual Search for Bing homepage images

I’ve posted here before about my love of the images that are used on the Bing homepage, and how I use them as my desktop wallpaper. I don’t know how long this has been up there, but I’ve just discovered Bing’s Visual Search for their archive of homepage images (340 of them as I write this). It’s a great way to view these fabulous images, so check it out at http://www.bing.com/visualsearch?g=binghp


bing


I should also add that I’m using the Bing Pictures Downloader app on Windows Phone 7 to save the images to my phone. Why would I want to do that? Well, WP7’s Pictures hub selects an image from the collection stored on the device to use as its background image and it also uses that for the Pictures live tile on the phone’s home screen – much of the time it selects one of the fantastic Bing Photos, like this:


PicturesHub