Picking Best Approach: Example Capitalizing Words (Part 1)

by Feb 10, 2023

In PowerShell, there are four separate sources of commands you can pick from when trying to solve a problem. In this mini-series, we look at all of them. The problem to solve is always the same: how to capitalize the first letter in a word. Note that this is an arbitrary problem we just picked as an example. The solution strategies apply to any problem you may want to solve with PowerShell.

The easiest way to solve a problem in PowerShell is to use the appropriate PowerShell cmdlet. You can use Get-Command to search for existing cmdlets. Unfortunately, there isn’t the perfect cmdlet for just *any* problem, so in this case you most likely won’t find one.

When that happens, PowerShell provides you with many approaches to solve your issue nonetheless. In todays’ solution we use PowerShell operators and .NET methods:

 $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 ' '

The result looks good:

This Is A Test Text

Tweet this Tip! Tweet this Tip!