Skip to content

Instantly share code, notes, and snippets.

@SimonWahlin
Created October 5, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimonWahlin/7e8a86f904379f19a141 to your computer and use it in GitHub Desktop.
Save SimonWahlin/7e8a86f904379f19a141 to your computer and use it in GitHub Desktop.
This function was written by Simon Wåhlin (@SimonWahlin) as an entry to the contest "Windows PowerShell TFM Book Contest and Giveaway" by Mike Robbins. Contest details can be found here:http://mikefrobbins.com/2015/09/23/windows-powershell-tfm-book-contest-and-giveaway/
<#
.Synopsis
Change first letter of each word in a string to uppercase and all other letters to lowercase.
.DESCRIPTION
PascalCase is the notation where the first letter of each word is written in UPPERCASE and the
rest of the letters are written in lowercase. Usually PascalCase does not contain spaces but
this function uses any whitespace char to determine the beginning of a new word.
.INPUTS
Takes one or many strings as input.
.OUTPUTS
Outputs strings formated with only first letter in each work in UPPERCASE
.EXAMPLE
'ThE wINDOWS PowerShell TFM book CONTEST aNd GiVeAwAy' | ConvertTo-SWPascalCase
The Windows Powershell Tfm Book Contest And Giveaway
.EXAMPLE
ConvertTo-SWPascalCase -InputString 'ThE wINDOWS PowerShell TFM book CONTEST aNd GiVeAwAy'
The Windows Powershell Tfm Book Contest And Giveaway
.NOTES
This function was written by Simon Wåhlin (@SimonWahlin) as an entry to the contest "Windows PowerShell TFM
Book Contest and Giveaway" by Mike Robbins.
Contest details can be found here:
http://mikefrobbins.com/2015/09/23/windows-powershell-tfm-book-contest-and-giveaway/
#>
function ConvertTo-SWPascalCase
{
[CmdletBinding(ConfirmImpact = 'None')]
[OutputType([string])]
Param
(
# Input string that will be converted to PascalCase
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
[String[]]
$InputString
)
Begin
{
$NewStringBuilder = New-Object -TypeName System.Text.StringBuilder
}
Process
{
Foreach($String in $InputString)
{
[System.Void]$NewStringBuilder.Clear()
# First char should alwayw be UpperCase
# non letter chars won't be effected
if($String[0])
{
[System.Void]$NewStringBuilder.Append($String[0].ToString().ToUpper())
}
# Loop through rest of string
for($i=1;$i-lt$String.Length;$i++)
{
if($String[($i-1)] -match '\S')
{
# Char follows a non-whitespace char, not beginning of word
[System.Void]$NewStringBuilder.Append($String[$i].ToString().ToLower())
}
else
{
# Char follows a whitespace char, begginning of word
[System.Void]$NewStringBuilder.Append($String[$i].ToString().ToUpper())
}
}
Write-Output -InputObject $NewStringBuilder.ToString()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment