Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function ConvertTo-TitleCase {
<#
.SYNOPSIS
Converts strings to Title Case
.DESCRIPTION
The ConverTo-TitleCase function capitalizes the first letter of each word in a string of text and converts the remaining letters in each word to lower case (Title Case).
.INPUTS
System.String
.OUTPUTS
System.String
.EXAMPLE
ConvertTo-TitleCase -String 'The wINDOWS PowerShell TFM book CONTEST aNd GiVeAwAy'
Output:
-------
The Windows Powershell Tfm Book Contest And Giveaway
Converts a string to upper case first letter and lower case remaining letters
.EXAMPLE
'The wINDOWS PowerShell TFM book CONTEST aNd GiVeAwAy' | ConvertTo-TitleCase
Output:
-------
The Windows Powershell Tfm Book Contest And Giveaway
Converts a string from pipeline to upper case first letter and lower case remaining letters
.EXAMPLE
'aNother weIRd STRING to conVerT', 'The wINDOWS PowerShell TFM book CONTEST aNd GiVeAwAy' | ConvertTo-TitleCase
Output:
-------
Another Weird String To Convert
The Windows Powershell Tfm Book Contest And Giveaway
Converts multiple strings from pipeline to upper case first letter and lower case remaining letters
#>
[CmdletBinding()]
Param(
# Specifies the string to convert to Title Case.
[Parameter(
Mandatory = $True,
ValueFromPipeLine = $True
)]
[ValidateNotNullOrEmpty()]
[String[]]
$String
)
PROCESS {
foreach ($Str in $String) {
$ConvertedWords = @()
# Split string into individual words
$Words = $Str -split ' '
foreach ($Word in $Words) {
# Check length of words to deal with multiple spaces in string
if ($Word.Length -gt 0) {
$ConvertedWords += "$($Word.Substring(0, 1).ToUpper())$($Word.Substring(1, $Word.Length -1).ToLower())"
}
else {
$ConvertedWords += ''
}
}
# Output converted string
Write-Output ($ConvertedWords -join ' ')
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment