Capitalizing First Letter of Every Word with Powershell 2

I came across the need to captalize the first letter of every word (I needed this for names, including hyphenated names) with PowerShell, and learned that PowerShell 2 has a great feature that comes in handy here.

I first tried using the PowerShell -replace operator but you can’t do function calls or anything complex in the replacement parameter.  So $name = $name -replace '\b(\w)', '$1.ToUpper()' doesn’t work.

If I were using C#, I would just use Regex.Replace, making use of a MatchEvaluator delegate (using lambda expression syntax): name = Regex.Replace(name, '\b(\w)', m => m.Value.ToUpper());

Thankfully, in PowerShell 2 you can now use an script block as a delegate. So my problem is solved with $name = [Regex]::Replace($name, '\b(\w)', { param($m) $m.Value.ToUpper() });.

If you’re unfamiliar with the MatchEvaluator, for each regular expression match encountered, the delegate function gets called and that function’s return value is the string used as the replacement. So in my example here, '\b(\w)' matches the first letter of every word. That letter gets passed to my script block as a .NET Match object, whose Value is the matched letter. The returned uppercase version of the letter is put back into the original string. Done!

Comments are closed.