Properly Capitalize a Title Using PowerShell

Being married to someone who majored in English has made me extra conscious of my spelling and capitalization. So, for my blog posts, I’ve written a script to help me ensure my titles are properly capitalized. It is not perfect (i.e. it doesn’t do a dictionary lookup), but it follows the basic APA guidelines. I thought I would share it, in case others would find it useful.

# Split the string into individual words
$words = $string.Split()
[System.Collections.Generic.List[PSObject]]$stringArray = @()
For($i = 0; $i -lt $words.Count; $i++){
    # Capitalize words of four or more letters, the first word, and the last word
    if($words[$i].Length -gt 3 -or $i -eq 0 -or $i -eq ($words.Count - 1)){
        # account for hyphen and capitalize words before and after
        $words[$i] = @($words[$i].Split('-') | ForEach-Object{
            $_.Substring(0,1).ToUpper() + $_.Substring(1,$_.Length-1)
        }) -join('-')
    } 
    # and the capitalized string to the array
    $stringArray.Add($words[$i])
}
# join the words back together to form your title
$stringArray -join(' ')


Example

PS C:\> $string = 'properly capitalize a title using PowerShell'
>> $words = $string.Split()
>> [System.Collections.Generic.List[PSObject]]$stringArray = @()
>> For($i = 0; $i -lt $words.Count; $i++){
>>     # Capitalize words of four or more letters, the first word, and the last word
>>     if($words[$i].Length -gt 3 -or $i -eq 0 -or $i -eq ($words.Count - 1)){
>>         # account for hyphen and capitalize words before and after
>>         $words[$i] = @($words[$i].Split('-') | ForEach-Object{
>>             $_.Substring(0,1).ToUpper() + $_.Substring(1,$_.Length-1)
>>         }) -join('-')
>>     }
>>     # and the capitalized string to the array
>>     $stringArray.Add($words[$i])
>> }
>> $stringArray -join(' ')

Properly Capitalize a Title Using PowerShell
  
String to lowercase
$string.ToLower()
Details
String to lowercase

Example
PS C:\> $string = "WILLIAMS"
>> $string.ToLower()

williams
  
String to uppercase
$string.ToUpper()
Details
String to uppercase

Example
PS C:\> $string = "williams"
>> $string.ToUpper()

WILLIAMS
  
String to uppercase on first letter only
$string.Substring(0,1).ToUpper() + $string.Substring(1,$string.Length-1).ToLower()
Details
String to uppercase on first letter only

Example
PS C:\> $string = "williams"
>> $string.Substring(0,1).ToUpper() + $string.Substring(1,$string.Length-1).ToLower()

Williams